繁体   English   中英

在组件级别上React / Redux链接异步thunk操作

[英]React/Redux chaining async thunk actions at component level

在组件级别上链接依赖的异步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)));
  });

您必须标识componentDidUpdate生命周期方法中出现的新用户响应,才能调用另一个从属调用。 像这样

export default class UserDetail extends React.Component {
  componentDidMount() {
    this.props.getUser();
  }
  componentDidUpdate(prevProps) {
    const { user, getBlogPostsForUser } = this.props;
    const { user: prevUser } = prevProps;
    if (prevUser !== user) {
      const { USER_ID } = user; // derive USER_ID from user object. I dont know path. you can accordingly change
      getBlogPostsForUser(USER_ID);
    }
  }
}

这应该工作。 欢迎反馈

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM