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

标签 javascript reactjs redux redux-thunk

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

相关文章:

javascript - react 俄罗斯方 block 。函数总是返回 false

reactjs - 如何使用react-transition-group设置退出动画

javascript - 如何让组件在ajax请求后重新渲染

angular - @select ng-redux 的 Jamine 单元测试错误

javascript - 带有 React-Native 和 mapStateToProps 的 Redux

javascript - Gruntjs 任务问题

javascript - JQuery 输入表单不起作用

javascript - 在单个 Backbone View 和 EJS 模板中使用多个模型的问题

javascript - 我可以为此函数编写 Flow 类型注释,将对象数组减少为一个对象吗?

javascript - 在 react-admin 中访问 redux store