使用Redux-thunk中间件实现异步数据请求

  action在到达store之前会经历一个中间件层,利用redux中间件机制,可以在action响应之前执行其他额外的业务逻辑。中间件指的是是action 与store的中间,是redux的中间件。  

1.先安装

npm install redux-thunk --save

2.在index.js里创建store时配置redux-thunk。

  要想使用中间件,需要在创建store的index.js文件里,引入applyMiddleware,照着官方的文档一步一步配置,使得store既使用了redux-thunk这个中间件,又使用了redux-doctools这个开发者工具。这样在action来的时候,会经过这些中间件,从而做额外的操作。

index.js:

import { createStore, applyMiddleware ,compose} from 'redux';
import reducer from './reducer'
import thunk from 'redux-thunk'
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?   window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const store=createStore(reducer,composeEnhancers(applyMiddleware(thunk)));
export default store;

3.在actionCreators.js的action 里写异步的代码

  因为有了thunk这个中间件,所以action可以是一个函数,这个函数有2个参数是dispatch、getState。store发现action 是一个函数,会自动执行这个函数。

actionCreators.js

import * as actionTypes from './actionTypes';
import{ fromJS } from 'immutable'
import axios from 'axios';
export const searchFocusAction=()=>({
    type:actionTypes.SEARCH_FOCUS
});
export const searchBlurAction=()=>({
    type:actionTypes.SEARCH_BLUR
});
export const listInitAction=(data)=>({
    type:actionTypes.LIST_INIT,
    data:fromJS(data)
});
export const getList=()=>{
       //action可以是一个函数,有dispatch参数
    return (dispatch)=>{
        axios.get('/api/headerList.json').then((res)=>{
            const data=res.data;
            dispatch(listInitAction(data.data))
        }).catch(()=>{
            console.log('error');
        });
    }    
};
原文地址:https://www.cnblogs.com/superlizhao/p/9437166.html