【发布时间】:2020-12-30 00:11:16
【问题描述】:
constructor(props) {
super(props);
this.state = {
myStateVar: []
}
}
static getDerivedStateFromProps(props, state) {
if (props.myStateVar !== state.myStateVar) {
return {
myStateVar: props.myStateVar
}
}
toggle() //Need to call the function each time when we get the props update
return null;
}
toggle() {
this.setState({
otherStateVar: []
})
}
我正在将我的 react 应用程序从 16.3 迁移到最新版本。我有一个问题,getDerivedStateFromProps() 不断调用,因为状态在 toggle() 中更新。我需要在道具更新时调用 toggle()
帮我解决问题。
【问题讨论】:
-
您可以为此使用 componentDidUpdate。
-
componentDidUpdate 不会正确获取道具更改/更新?
-
componentDidUpdate 将使用 prevProps 作为参数调用。你可以在那里检查情况。我添加了一个反映它的答案
标签: reactjs react-native