Redux-thunk

  1. redux-thunk 下载
    1. npm install redux-thunk
  1. 引入 redux-thunk
    1. import thunk from 'redux-thunk';
  1. 注册 redux-thunk
    1. import { applyMiddleware } from 'redux';
    2. createStore(rootReducer, applyMiddleware(thunk));
  1. 使用 redux-thunk
    1. const loadPosts = () => async dispatch => {
    2. const posts = await axios.get('/api/posts').then(res => res.data);
    3. dispatch({
    4. type: LOADPOSTSUCCESS,
    5. payload: posts
    6. })
    7. }
  1. redux-thunk 源码
    判断传入的action是异步函数还是对象,如果是函数先执行函数,函数执行结束之后再传入reducer中。
    1. export default ({dispatch}) => next => action => {
    2. if (typeof action === 'function') {
    3. return action(dispatch);
    4. }
    5. next(action);
    6. }