shouldComponentUpdate中的突变状态反应16.6.3



由于react已经否决了它们的许多Lifecycle Methods,我发现,当使用reduxconnect时,当我想增强component的本地状态时,我正在使用componentDidUpdate。问题是只有prevProps, prevState被传递给这个函数。

这意味着我在shouldComponentUpdate生命周期中只有nextProps, nextState

对我来说,这样做本质上是错误的:

shouldComponentUpdate(nextProps) {
const { status_status } = nextProps;
if(status_status === "error") {
this.props.dispatch(resetStatus());
}
return true;
}

这肯定是antiPattern,我不应该这么做。

那么,如果不使用shouldComponentUpdate,我如何获得nextProps

我也遇到过类似的情况,我发现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感觉良好,那么你可以发表你的意见和想法作为答案。

最新更新