mapDispatchToProps 应该调度初始化操作吗? [英] Should mapDispatchToProps dispatch initialization actions?

查看:18
本文介绍了mapDispatchToProps 应该调度初始化操作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一个无状态的、功能性的 UserProfile 组件显示给定 url 的用户数据.假设它被 connect(mapStateToProps, mapDispatchToProps)(UserProfile) 包裹.最后,假设一个化简为 state.userProfile 的 reducer.每当 url 更改时,我都需要重新初始化 state.userProfile,因此想到的解决方案是从 mapDispatchToProps 中执行此操作,如下所示:

Suppose a stateless, functional UserProfile component that displays user data for the given url. Suppose it is being wrapped with connect(mapStateToProps, mapDispatchToProps)(UserProfile). Finally, suppose a reducer that reduces into state.userProfile. Anytime the url changes, I need to re-initialize the state.userProfile, so a solution that comes to mind is to do so from within the mapDispatchToProps like so:

function mapDispatchToProps(dispatch, ownProps) {
  dispatch(fetchUser(ownProps.userId))
  return {
    ...
  }
}

假设 thunked fetchUser 通过与当前状态进行比较来忽略重复调用,这是一种可以接受的做法吗?或者从这个 map 函数立即调用 dispatch 会不会有问题?

Provided that the thunked fetchUser ignores repeated calls by comparing with current state, is this an acceptable practice? Or are there problems associated with calling dispatch immediately from this map function?

推荐答案

这是不受支持的,随时可能中断.
mapDispatchToProps 本身不应该有副作用.

This is unsupported and can break at any time.
mapDispatchToProps itself should not have side effects.

如果您需要调度操作以响应 prop 更改,您可以创建一个组件类并为此使用生命周期方法:

If you need to dispatch actions in response to prop changes, you can create a component class and use lifecycle methods for this:

class UserProfile extends Component {
  componentDidMount() {
    this.props.fetchUser(this.props.id)
  }

  componentDidUpdate(prevProps) {
    if (prevProps.id !== this.props.id) {
      this.props.fetchUser(this.props.id)
    }
  }

  // ...

}

这篇关于mapDispatchToProps 应该调度初始化操作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆