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

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

问题描述

假设一个无状态的,功能性的 UserProfile 组件,它显示给定网址的用户数据。假设它被 connect(mapStateToProps,mapDispatchToProps)(UserProfile)包裹。最后,假设一个reducer减少到 state.userProfile 。每当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忽略通过与当前状态进行比较重复呼叫,这是可接受的做法吗?或者是否存在与此地图函数立即调用调度相关的问题?

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?

推荐答案

这是不受支持的,并且可以随时中断。< br>
mapDispatchToProps 本身不应有副作用。

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

如果你需要派遣行动作为回应为了支持更改,您可以创建一个组件类并使用生命周期方法:

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天全站免登陆