尝试在我的组件中将多个操作链接在一起

Trying to chain multiple actions together in my component

在我的 React 组件中,我试图将多个操作链接在一起,如下所示:

componentDidMount() {
  dispatch(Actions.fetchUser(userId)).then(() => {
    dispatch(Actions.fetchAbc(abcId)).then(() => {
      dispatch(Actions.fetchDef(defId));
    });
  });     
}

每个操作都遵循与 fetchUser 相同的模式,其中 returns 调度:

fetchUser: (userId) => {
  return dispatch => {
    let url = "....";
    axios.get(url)
      .then(function(resp) {        
        dispatch({
          type: Constants.SomeAction,
          user: resp.data.user,
        });
      });
  };
},

在我的组件中我看到一个错误:

Uncaught TypeError: Cannot read property 'then' of undefined

错误与第一个 .then 调用 (fetchUser) 在同一行。

这不是将我的行为串联起来的正确方法吗?

时间明智我必须一个接一个地做。

调度一个 thunk returns 是 thunk 函数的 return 值,但你的 return 没有任何东西。尝试:

fetchUser: (userId) => {
  return dispatch => {
    let url = "....";
    // return the promise so you can chain on it
    return axios.get(url)
      .then(function(resp) {        
        dispatch({
          type: Constants.SomeAction,
          user: resp.data.user,
        });
      });
  };
},

您需要确保您 return 是 axios 编辑的 return 承诺,因为这是您想要与后续 then.


从更广泛的角度来看,您必须确保以特定顺序分派操作的情况会有所不同,具体取决于您的操作是同步的还是异步的(您的异步操作通常 return承诺)。

同步事件很简单,你可以简单地按顺序调用它们:

dispatch(syncAction1())
dispatch(syncAction2())
dispatch(syncAction3())

对于异步操作,您需要确保每个操作 return 都是一个承诺,然后将它们链接起来(重写您的 componentDidMount 函数以指出其他一些问题):

dispatch(Actions.fetchUser(userId))
  // You need to ensure that your handler functions returns the result of the
  // next async dispatch
  .then(() => {
    return dispatch(Actions.fetchAbc(abcId))
  })
  // More simply, if you're only doing on thing then you can use the shorter
  // form of arrow function, which implicitly returns the result      
  .then(() => dispatch(Actions.fetchDef(defId))

如果您遇到需要两者结合的情况,您也可以这样做:

dispatch(syncAction1())
dispatch(asyncAction2())
  .then(() => {
    dispatch(syncAction3())
    return dispatch(asyncAction4())
  })
  .then(() => dispatch(asyncAction5))

(其中异步操作是 return 承诺的 thunk,但同步操作可以是普通对象或同步 thunk。)