Why do we need middleware for async flow in Redux?

前端 未结 11 2231
忘了有多久
忘了有多久 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 05:08

    To Answer the question:

    Why can't the container component call the async API, and then dispatch the actions?

    I would say for at least two reasons:

    The first reason is the separation of concerns, it's not the job of the action creator to call the api and get data back, you have to have to pass two argument to your action creator function, the action type and a payload.

    The second reason is because the redux store is waiting for a plain object with mandatory action type and optionally a payload (but here you have to pass the payload too).

    The action creator should be a plain object like below:

    function addTodo(text) {
      return {
        type: ADD_TODO,
        text
      }
    }
    

    And the job of Redux-Thunk midleware to dispache the result of your api call to the appropriate action.

提交回复
热议问题