[英]Mutating state in shouldComponentUpdate react 16.6.3
Since react have deprecated many of their Lifecycle Methods
I found that, when using redux
and connect
when I want to augment local state of a component
I am using componentDidUpdate
. 由于react已弃用了许多
Lifecycle Methods
我发现,当使用redux
和connect
时,我想使用componentDidUpdate
来扩展component
本地状态。 The problem is only prevProps, prevState
are passed to this function. 问题是只有
prevProps, prevState
才传递给此函数。
That then means I only have nextProps, nextState
inside the shouldComponentUpdate
lifeCycle`. 这意味着我
nextProps, nextState
在shouldComponentUpdate
lifeCycle`中只有nextProps, nextState
nextState。
To me this feels inherently wrong to do something as follows: 对我来说,执行以下操作本质上是错误的:
shouldComponentUpdate(nextProps) {
const { status_status } = nextProps;
if(status_status === "error") {
this.props.dispatch(resetStatus());
}
return true;
}
This is surely an antiPattern
and I should not be doing this. 这肯定是一个
antiPattern
,我不应该这样做。
How can I then get the nextProps
without using shouldComponentUpdate
我怎样才能再拿到
nextProps
不使用shouldComponentUpdate
I was having similar case and I had found getDerivedStateFromProps useful and suitable in such condition. 我有类似的情况,我发现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
}
I know this note from the docs : 我从文档中知道此注释:
If you need to perform a side effect (for example, data fetching or an animation) in response to a change in props, use componentDidUpdate lifecycle instead.
如果您需要根据道具的变化执行副作用(例如,数据获取或动画),请改用componentDidUpdate生命周期。
But I am just sharing my experience that was only the case getDerivedStateFromProps
working. 但是我只是分享我的经验,只有
getDerivedStateFromProps
工作的情况。
However, I would also suggest you to use componentDidUpdate
hook first. 但是,我也建议您先使用
componentDidUpdate
挂钩。 And if everything seems good for you, then stick with it. 如果一切对您都有利,那就坚持下去。 Or if you also face using
componentDidUpdate
and feel alright using getDerivedStateFromProps
then you may post your opinion and ideas as an answer. 或者,如果您也面对使用
componentDidUpdate
并使用getDerivedStateFromProps
感觉还不错,那么您可以发表自己的见解和想法作为答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.