【问题标题】:React/Redux chaining async thunk actions at component levelReact/Redux 在组件级别链接异步 thunk 操作
【发布时间】:2019-04-01 10:00:38
【问题描述】:

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

我的用例是一个流程,我需要首先进行 api 调用以检索用户对象,然后获取该用户的所有博客文章。需要注意的是,第二次获取所有博客文章的调用取决于第一次调用的返回值(用户 ID)。

我的组件:

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

this.props.getUser() 返回一个我映射到道具的用户对象:

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

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

【问题讨论】:

    标签: javascript reactjs redux redux-thunk


    【解决方案1】:

    你可以链接 thunk

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

    【讨论】:

      【解决方案2】:

      您必须识别 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);
          }
        }
      }
      

      这应该可行。欢迎反馈

      【讨论】:

        猜你喜欢
        • 2018-01-31
        • 1970-01-01
        • 2017-09-26
        • 1970-01-01
        • 2021-10-04
        • 2018-02-28
        • 2019-12-17
        • 2017-03-03
        • 2023-03-09
        相关资源
        最近更新 更多