[英]setState does not update state
why this.setState does not work. 为什么this.setState不起作用。
constructor(props) {
super(props);
this.state ={
obj: [],
}
}
,
componentDidUpdate(prevProps){
const { obj } = this.props;
this.setState({obj});
}
}
If you look at your dev console you'll see an error when that console log is supposed to occur, because you're using a "normal" function without any kind of this
preservation. 如果你看一下你的开发者控制台,你会看到一个错误时控制台日志应该发生,因为您使用的是“正常”的功能,没有任何形式的
this
保存。 Instead, once that function gets called the this
identifier will be referencing the global context (eg window
), rather than your component. 相反,一旦调用该函数,
this
标识符将引用全局上下文(例如window
),而不是您的组件。
Use an arrow function to make sure this
is the one you actually meant, and you'll see that setState
worked just fine: 使用箭头功能确保
this
是您真正想要的功能,并且您会看到setState
工作:
componentDidUpdate(prevProps){
this.setState({
siteDataState: this.props.siteData
}, () => {
console.log(this.state.siteDataState);
});
}
That said, this is going to cascade-trigger because you're changing the component in the function that triggers when the component changes , so put some if
code in there that makes sure that this.state.siteDataState
isn't already what's in this.props.siteData
. 就是说,这将进行级联触发,因为您正在更改组件更改时触发的函数中的组件 ,因此请在其中放置一些
if
代码,以确保this.state.siteDataState
尚未包含 this.props.siteData
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.