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通过与当前状态进行比较而忽略重复调用,这是否可以接受?或者是否存在与此地图功能立即调用调度相关的问题?
这是不受支持的,可以随时中断.
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)
| 归档时间: |
|
| 查看次数: |
1233 次 |
| 最近记录: |