javascript 反应中的 componentDidUpdate 与 componentWillReceiveProps 用例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49386324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
componentDidUpdate vs componentWillReceiveProps use case in react
提问by Jamie Aden
This is how we use componentWillReceiveProps
这就是我们如何使用 componentWillReceiveProps
componentWillReceiveProps(nextProps) {
if(nextProps.myProp !== this.props.myProps) {
// nextProps.myProp has a different value than our current prop
}
}
It's very similar to componentDidUpdate
它非常类似于 componentDidUpdate
componentDidUpdate(prevProps) {
if(prevProps.myProps !== this.props.myProp) {
// this.props.myProp has a different value
// ...
}
}
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 componentDidUpdateis 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 中执行 setState,render 将触发两次,并且 componentWillReceiveProps 的参数是 nextProps,而参数componentDidUpdate是 prevProp,但我真的不知道何时使用它们。我经常使用componentDidUpdate,但使用 prevState,比如更改下拉状态并调用 api
eg.
例如。
componentDidUpdate(prevProps, prevState) {
if(prevState.seleted !== this.state.seleted) {
this.setState({ selected: something}, ()=> callAPI())
}
}
回答by Nick Zuber
The main difference between the two is:
两者的主要区别在于:
- When they are called in a component's lifecycle
- How it updates component
state
- 当它们在组件的生命周期中被调用时
- 它如何更新组件
state
When are they called?
他们什么时候叫?
As the names suggest – and as you probably know since you mentioned "if I do setState in componentDidUpdate, render will trigger twice" – componentDidUpdateis called afterthe component updates (received new props or state). This is why the parameters to this function is prevPropsand prevState.
顾名思义——正如你可能知道的,因为你提到“如果我在 componentDidUpdate 中设置了 setState,渲染将触发两次”——在组件更新(接收到新的道具或状态)之后componentDidUpdate被调用。这就是为什么这个函数的参数是and 的原因。prevPropsprevState
So if you wanted to do something beforethe component received new props, you'd use componentWillReceiveProps, and if you wanted to do something afterit received new props or state, you'd use componentDidUpdate.
所以如果你想在组件收到新的 props之前做一些事情,你会使用componentWillReceiveProps,如果你想在收到新的 props 或 state之后做一些事情,你会使用componentDidUpdate.
How do they update state?
他们如何更新state?
The main difference here is:
这里的主要区别是:
componentWillReceivePropswill update state synchronouslycomponentDidUpdatewill update state asynchronously.
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.
这很重要,因为在尝试将状态与组件 props 的其他部分同步时,可能会出现一些问题。

