[英]Mutating state in shouldComponentUpdate react 16.6.3
由于react已弃用了许多Lifecycle Methods
我发现,当使用redux
和connect
时,我想使用componentDidUpdate
来扩展component
本地状态。 问题是只有prevProps, prevState
才传递给此函数。
这意味着我nextProps, nextState
在shouldComponentUpdate
lifeCycle`中只有nextProps, nextState
nextState。
对我来说,执行以下操作本质上是错误的:
shouldComponentUpdate(nextProps) {
const { status_status } = nextProps;
if(status_status === "error") {
this.props.dispatch(resetStatus());
}
return true;
}
这肯定是一个antiPattern
,我不应该这样做。
我怎样才能再拿到nextProps
不使用shouldComponentUpdate
我有类似的情况,我发现getDerivedStateFromProps在这种情况下有用且合适。
static getDerivedStateFromProps(props, state) {
// now, you may dispatch checking the condition
// BTW, you will dispatch just using props
// props.dispatch()
// this.props.dispatch() // invalid
}
我从文档中知道此注释:
如果您需要根据道具的变化执行副作用(例如,数据获取或动画),请改用componentDidUpdate生命周期。
但是我只是分享我的经验,只有getDerivedStateFromProps
工作的情况。
但是,我也建议您先使用componentDidUpdate
挂钩。 如果一切对您都有利,那就坚持下去。 或者,如果您也面对使用componentDidUpdate
并使用getDerivedStateFromProps
感觉还不错,那么您可以发表自己的见解和想法作为答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.