首页 文章

为什么Redux将调度传递给动作的返回函数?

提问于
浏览
1

完整的初学者,就Redux React(和ES6)而言,请耐心等待我 - 我仍然有点困惑 . 继一个教程之后,Redux actions 之一开始于:

export function getApiData(){
       return(dispatch) => {return(dispatch) => { -some other actions here- }
}

此函数从API获取数据,因此它还调度getApiDataRequested和GetApiData成功操作,但上面对我没有意义 . 现在我知道调度发出更新Redux状态的意图,但为什么dispatch在return函数中作为参数传递?

干杯!

1 回答

  • 4

    这是因为它是使用Redux-thunk进行异步操作的一个例子 . 如果您查看此中间件,它会检查您的操作是否为函数,如果是,则会将调度传递给返回的函数 . 你不能只在redux中调用一个动作,你总是要调度它,所以你应该使用dispatch对象来调用你的动作 .

    function createThunkMiddleware(extraArgument) {
      return ({ dispatch, getState }) => next => action => {
        if (typeof action === 'function') {
          return action(dispatch, getState, extraArgument);
        }
    
        return next(action);
      };
    }
    

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

相关问题