mapDispatchToProps应该调度初始化操作吗?

Bij*_*lle 2 javascript redux react-redux

假设一个无状态的功能UserProfile组件显示给定URL的用户数据.假设它被包裹着connect(mapStateToProps, mapDispatchToProps)(UserProfile).最后,假设减速器减少到state.userProfile.每当url发生变化时,我都需要重新初始化state.userProfile,所以想到的解决方案就是在mapDispatchToProps中这样做:

function mapDispatchToProps(dispatch, ownProps) {
  dispatch(fetchUser(ownProps.userId))
  return {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

如果thunked fetchUser通过与当前状态进行比较而忽略重复调用,这是否可以接受?或者是否存在与此地图功能立即调用调度相关的问题?

Dan*_*mov 5

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

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

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

  // ...

}
Run Code Online (Sandbox Code Playgroud)

  • 来自维基百科:"对结果的评估不会导致任何语义上可观察到的副作用".调度是一种副作用,因为它会更改应用程序的全局(原子可变)状态. (2认同)