Why do we need middleware for async flow in Redux?

前端 未结 11 2242
忘了有多久
忘了有多久 2020-11-22 04:17

According to the docs, \"Without middleware, Redux store only supports synchronous data flow\". I don\'t understand why this is the case. Why can\'t the container component

11条回答
  •  再見小時候
    2020-11-22 04:53

    Redux can't return a function instead of an action. It's just a fact. That's why people use Thunk. Read these 14 lines of code to see how it allows the async cycle to work with some added function layering:

    function createThunkMiddleware(extraArgument) {
      return ({ dispatch, getState }) => (next) => (action) => {
        if (typeof action === 'function') {
          return action(dispatch, getState, extraArgument);
        }
    
        return next(action);
      };
    }
    
    const thunk = createThunkMiddleware();
    thunk.withExtraArgument = createThunkMiddleware;
    
    export default thunk;
    

    https://github.com/reduxjs/redux-thunk

提交回复
热议问题