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

React/Redux chaining async thunk actions at component level

在组件级别链接依赖异步 redux thunk 操作的推荐方法是什么?

我的用例是一个流程,我需要首先调用 api 来检索用户对象,然后获取该用户的所有博客文章。问题是第二次调用获取所有博客文章取决于第一次调用 return value (user id).

我的组件:

export default class UserDetail extends React.Component
{
  componentDidMount() {
    this.props.getUser()
  }
}

this.props.getUser() return我映射到道具的用户对象:

const mapStateToProps = (state) => {
  return {
    user: state.user
  }
}

我需要在 this.props.getUser() 完成后调用 this.props.getBlogPostsForUser(USER_ID)。以这种方式链接操作的推荐最佳做法是什么?

您必须确定来自 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);
    }
  }
}

这应该有效。欢迎反馈

你可以链接 thunks

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)));
  });