redux - 如何在 Redux 中处理两个连续和依赖的 Async 调用?

标签 redux

我通过调用操作 fetchPosts 异步获取帖子列表来自 componentDidMount 上的组件.我想,一旦该请求被相关的 reducer (更新状态)接收并处理,调用另一个 Action fetchPostsMetaData , 带有一组刚收到的帖子的 ID。

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

解决这个问题的最佳方法是什么?我试过谷歌搜索,但找不到相关的例子/答案。

最佳答案

使用 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
}

这是 redux-thunk 的一个非常标准的用例.上面的示例迎合了您提出问题的方式,但您可以在看起来像 redux-thunk 的单个 Action 创建器中完成此操作。此处提供的示例: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 });
      })
  }
}

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

关于redux - 如何在 Redux 中处理两个连续和依赖的 Async 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33342971/

相关文章:

reactjs - 使用 Redux 表单对 FormSection 进行验证

javascript - React,Array obj 上的 TypeError(this.props.data.map 不是函数)

unit-testing - Enzyme:如何测试作为 prop 传递的 onSubmit 函数?

reactjs - React + React Native 入门套件

javascript - React-redux connect 传递 Prop 太晚了

javascript - react-redux-form 单选字段不更新选中的 Prop

javascript - 在提供 css 属性时,内联未在 Material ui 中定义

reactjs - 何时以及如何在react/router/redux应用程序中获取详细 View 的数据?

javascript - 未捕获的类型错误 : Cannot read property 'touched' of undefined

javascript - 如何在 Redux 中使用 reducer 进行多个操作?