假设一个无状态的功能性UserProfile
组件显示给定URL的用户数据。假设它被connect(mapStateToProps, mapDispatchToProps)(UserProfile)
包装。最后,假设一个还原器还原为state.userProfile
。每当url更改时,我都需要重新初始化state.userProfile
,因此想到的解决方案是从mapDispatchToProps内部进行,如下所示:
function mapDispatchToProps(dispatch, ownProps) {
dispatch(fetchUser(ownProps.userId))
return {
...
}
}
假设笨拙的fetchUser通过与当前状态进行比较来忽略重复调用,这是否可以接受?还是有与此 map 函数立即调用dispatch相关的问题?
最佳答案
不支持此功能,并且可以随时中断。mapDispatchToProps
本身不应该有副作用。
如果您需要分派(dispatch)操作以响应 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)
}
}
// ...
}
关于javascript - mapDispatchToProps是否应该调度初始化 Action ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36654197/