问题描述
这就是我们使用 componentWillReceiveProps
componentWillReceiveProps(nextProps) {
if(nextProps.myProp !== this.props.myProps) {
// nextProps.myProp has a different value than our current prop
}
}
它与 componentDidUpdate
componentDidUpdate(prevProps) {
if(prevProps.myProps !== this.props.myProp) {
// this.props.myProp has a different value
// ...
}
}
我可以看到一些差异,例如如果我在componentDidUpdate中执行setState,则渲染将触发两次,并且componentWillReceiveProps的参数为nextProps,而 componentDidUpdate
的参数为prevProp,但严重的是我没有知道何时使用它们.我经常使用 componentDidUpdate
,但对于prevState,例如更改下拉状态并调用api
I can see some differences, like if I do setState in componentDidUpdate, render will trigger twice, and the argument for componentWillReceiveProps is nextProps, while argument for componentDidUpdate
is prevProp, but seriously I don't know when to use them. I often use componentDidUpdate
, but with prevState, like change a dropdown state and call api
例如
componentDidUpdate(prevProps, prevState) {
if(prevState.seleted !== this.state.seleted) {
this.setState({ selected: something}, ()=> callAPI())
}
}
推荐答案
两者之间的主要区别是:
The main difference between the two is:
- 在组件的生命周期中调用它们时
- 它如何更新组件
状态
顾名思义,您可能已经知道,因为您提到如果我在componentDidUpdate中执行setState,则渲染将触发两次" – componentDidUpdate
在组件之后称为更新(收到新道具或状态).这就是为什么此函数的参数为 prevProps
和 prevState
的原因.
As the names suggest – and as you probably know since you mentioned "if I do setState in componentDidUpdate, render will trigger twice" – componentDidUpdate
is called after the component updates (received new props or state). This is why the parameters to this function is prevProps
and prevState
.
因此,如果您想在组件收到新道具之前之前做某事,则可以使用 componentWillReceiveProps
,并且如果您想在之后做某事它收到了新的道具或状态,则可以使用 componentDidUpdate
.
So if you wanted to do something before the component received new props, you'd use componentWillReceiveProps
, and if you wanted to do something after it received new props or state, you'd use componentDidUpdate
.
这里的主要区别是:
componentWillReceiveProps
will update state synchronouslycomponentDidUpdate
will update state asynchronously.
这很重要,因为在尝试与组件的props的其他部分同步状态时,可能会出现一些问题.
This can be important as there are some gotchya's that can come up when trying to sync state with other parts of your component's props.
这篇关于componentDidUpdate与componentWillReceiveProps在用例中的用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!