如何在 Redux 中处理两个连续和依赖的 Async 调用? [英] How to handle two consecutive and dependent Async calls in Redux?
问题描述
我通过从 componentDidMount
上的组件调用操作 fetchPosts
异步获取帖子列表.我想,一旦该请求被相关的减速器(它更新状态)接收并处理,就调用另一个动作 fetchPostsMetaData
,并使用刚刚接收到的帖子的 id 数组.
I am getting a list of posts asynchronously by calling an action fetchPosts
from a Component on componentDidMount
. I would like, once that request is received and handled by the relevant reducer (which updates the state), to call another action fetchPostsMetaData
, with an array of the just-received posts' ids.
我正在使用 redux-thunk
中间件,并使用 jQuery.ajax
I am using redux-thunk
middleware, and making my ajax requests using jQuery.ajax
解决这个问题的最佳方法是什么?我试过谷歌搜索,但找不到相关的例子/答案.
What is the best way to go about this? I tried googling but couldn't find a relevant example / answer.
推荐答案
使用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
示例的单个动作创建器中完成此操作:http://redux.js.org/docs/advanced/AsyncActions.html
This is a pretty standard use-case for redux-thunk
. The above example is catered towards the way you're asking the question, but you could accomplish this in a single action creator that looks the the redux-thunk
example provided here: http://redux.js.org/docs/advanced/AsyncActions.html
不同的是,在我的示例中,我在 thunk 内部调度 thunk,而不是直接在第一个 thunk 内部执行第二个任务.所以它相当于:
Whats different is that in my example, I'm dispatching a thunk inside of a thunk, rather than doing the second task directly inside of the first thunk. So its equivalent to this:
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 }
这样的操作时,它是同步的,并且在您调度以下异步操作之前,reducer 会更新.
You won't run into any race conditions because when you dispatch an action like { type: RECEIVE_POSTS, payload: res }
, it is synchronous and the reducer updates before you dispatch the following async action.
这篇关于如何在 Redux 中处理两个连续和依赖的 Async 调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!