【发布时间】:2018-11-26 12:50:45
【问题描述】:
由于 react 已经弃用了他们的许多 Lifecycle Methods,我发现,当我想增加 component 的本地状态时,我使用 componentDidUpdate。问题是只有prevProps, prevState 被传递给这个函数。
那意味着我在 shouldComponentUpdate lifeCycle` 中只有 nextProps, nextState。
对我来说,做以下事情是天生错误的:
shouldComponentUpdate(nextProps) {
const { status_status } = nextProps;
if(status_status === "error") {
this.props.dispatch(resetStatus());
}
return true;
}
这肯定是antiPattern,我不应该这样做。
我怎样才能在不使用shouldComponentUpdate的情况下获得nextProps
【问题讨论】:
-
你为什么不用
componentDidUpdate,它应该可以处理这样的副作用。componentDidUpdate(prevProps) { const { status } = this.props; if(status !== prevProps.status_status && status === "error") { this.props.dispatch(resetStatus()); } } -
^ 恕我直言,这看起来是一个可靠的答案。
-
啊,为什么@ShubhamKhatri 此时
this.props是当前状态 -
@JamieHutber,nextProps 将在渲染周期之后成为 currentProps,并且在状态渲染之后调用 sideEffects 比之前完美且稳定,这就是不推荐使用 componentWillReceiveProps 的原因
-
谢谢朋友,如果你能添加这个作为答案,我会接受它。
标签: javascript reactjs redux