Redux 操作创建者在另一个内部调用一个

Redux action creators invoke one inside another

本文关键字:一个 调用 内部 操作 创建者 另一个 Redux      更新时间:2023-09-26

我在Redux中使用鸭子,但这应该与问题无关。我在同一个文件中有几个动作创建者,我想从另一个中调用一个(希望不必为下面的 SWITCH 中的每个 CASE 重复调度):

...
export function closeAuthDialogs() {
  return {type: CLOSE_AUTH_DIALOGS}
}
export function openDialog(dialog) {
  // close any open dialogs
  dispatch => {dispatch(closeAuthDialogs())} // <--THIS DOES NOT GET CALLED!!!
  //open the one we need
  switch (dialog) {
    case 'login':
      return {type: OPEN_LOGIN}
    case 'register':
      return {type: OPEN_REGISTER}
    case 'forgot':
      return {type: OPEN_FORGOT}
    case 'change':
      return {type: OPEN_CHANGE}
    case 'profile':
      return {type: OPEN_PROFILE}
    default:
      return;
  }
}
...

打开工作正常,但关闭函数永远不会被触发。有没有办法从打开函数中调用关闭函数,而无需在打开函数的开关中为每个 CASE 重复调度?

通过双重调度,我的意思是...

return dispatch => {
  dispatch({type: CLOSE_AUTH_DIALOGS})
  dispatch({type: OPEN_SOME_DIALOG)}
}

如果可能的话,我只想调用收盘价一次,然后返回指定的开盘价。

啪!

你需要使用像redux-thunk这样的中间件。这里的安装说明,但基本上你需要在设置商店时应用它:

const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

这将允许您从操作返回函数。 像这样的事情应该这样做:

export function openDialog(dialog) {
  return (dispatch) => {
    dispatch(closeAuthDialogs());
    switch (dialog) {
      case 'login':
        return dispatch({type: OPEN_LOGIN})
      case 'register':
        return dispatch({type: OPEN_REGISTER})
      case 'forgot':
        return dispatch({type: OPEN_FORGOT})
      case 'change':
        return dispatch({type: OPEN_CHANGE})
      case 'profile':
        return dispatch({type: OPEN_PROFILE})
      default:
        return;
    }
  }
}