我通过从componentDidMount上的组件调用fetchPosts来异步获取帖子列表.我希望,一旦该请求被相关的reducer(更新状态)接收和处理,就可以使用刚接收到的帖子ids的数组来调用另一个动作fetchPostsMetaData.
我正在使用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示例: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 }); }) } }
您不会遇到任何竞争条件,因为当您分派{类型:RECEIVE_POSTS,payload:res}时,它是同步的,并且reducer在发送以下异步操作之前更新.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。