如何在Redux中处理两个连续和依赖的异步调用?

lio*_*ior 15 redux

我通过调用fetchPostsComponent上的一个动作来异步获取一个帖子列表componentDidMount.我希望,一旦该请求被相关的reducer(更新状态)接收并处理,就可以调用另一个动作fetchPostsMetaData,其中包含一系列刚收到的帖子ID.

我正在使用redux-thunk中间件,并使用我的ajax请求jQuery.ajax

最好的方法是什么?我尝试使用谷歌搜索,但找不到相关的示例/答案.

Nat*_*gen 11

使用redux-thunk:

class PostIndex extends React.Component {
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch(getPosts());
  }
  ...
}

function fetchPosts() {
  return dispatch => {
    fetchPostsAjax()
      .then(res => {
        dispatch({ type: 'RECEIVE_POSTS', payload: res });
        dispatch(fetchPostMeta(res));
      })
  }
}

function fetchPostMeta(posts) {
  return dispatch => {
    fetchPostMetaAjax(posts)
      .then(res => dispatch({ type: 'RECEIVE_POST_META', payload: res }));
    }
  }
}

function fetchPostAjax() {
   // return a promise, whether from jQuery.ajax or fetch
}

function fetchPostMetaAjax() {
  // return a promise
}
Run Code Online (Sandbox Code Playgroud)

这是一个非常标准的用例redux-thunk.上面的示例迎合了您提出问题的方式,但您可以在单个操作创建器中完成此操作,该创建器查看redux-thunk此处提供的示例:http://redux.js.org/docs/advanced/AsyncActions.html

不同的是,在我的例子中,我正在thunk中发送一个thunk,而不是直接在第一个thunk内部执行第二个任务.所以它相当于:

function fetchPosts() {
  return dispatch => {
    fetchPostsAsync()
      .then(res => { // res is posts
        dispatch({ type: 'RECEIVE_POSTS', payload: res });
        return fetchPostMetaAsync(res);
      })
      .then(res => { // res  is metadata
        dispatch({ type: 'RECEIVE_POST_META', payload: res });
      })
  }
}
Run Code Online (Sandbox Code Playgroud)

您不会遇到任何竞争条件,因为当您调度类似的操作时{ type: RECEIVE_POSTS, payload: res },它是同步的,并且在您调度以下异步操作之前,reducer会更新.