在组件级别链接依赖的异步 redux thunk 操作的推荐方法是什么?
我的用例是一个流程,我需要首先进行 api 调用来检索用户对象,然后获取该用户的所有博客文章。问题是,获取所有博客文章的第二次调用取决于第一次调用的返回值(用户 ID)。
我的组件:
export default class UserDetail extends React.Component
{
componentDidMount() {
this.props.getUser()
}
}
this.props.getUser()
返回一个我映射到 props 的用户对象:
const mapStateToProps = (state) => {
return {
user: state.user
}
}
我需要在 this.props.getUser()
完成后调用 this.props.getBlogPostsForUser(USER_ID)
。以这种方式链接操作的推荐最佳实践是什么?
最佳答案
你可以链接重击
const getUser = username => dispatch => request(username)
.then(res => dispatch({ type: GET_USER })
.catch(err => dispatch({ type: GET_USER_ERR }));
const getBlogPostsForUser = userId => dispatch => request(userId)
.then(res => dispatch({ type: GET_BLOGS }))
.catch(err => dispatch({ type: GET_BLOGS_ERR }));
const getUserAndPosts = username => (dispatch, getState) => dispatch(getUser(username))
.then(() => {
const user = getState().user;
return dispatch(getBlogPostsForUser(user.id));
});
或者您可以将它们合并到一个调度中,然后将它们捆绑在一起
const getUserAndPosts = (username) => dispatch => request(username)
.then((userData) => {
dispatch(setUser(userData));
return request(user.id)
.then(blogs => dispatch(setBlog(blogs)));
});
关于javascript - React/Redux 在组件级别链接异步 thunk 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53029104/