gpt4 book ai didi

node.js - 状态未正确设置 - React Native

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:59 26 4
gpt4 key购买 nike

我对从代码中得到的内容感到非常困惑。我有以下内容应该注销 data.points 然后将 this.state.points 设置为 data.points 然后注销 this.state.points,但是当它注销它们时,它们并不相等。这是我正在使用的准确代码,所以我确信这就是输出的内容。我可能忽略了一些东西,但我花了一个小时阅读并注销了这段代码,但我仍然无法弄清楚。这是我运行的代码:

console.log(data.points);

if (!this.state.hasPressed) {
this.setState({points: data.points})
console.log('in not hasPressed if');
}

console.log(this.state.points);

但是在 chrome 远程调试器中我得到了这个:

["114556548393525038426"]

in not hasPressed if

[]

最佳答案

setState 是一个异步调用。您必须使用函数回调来等待 setState 完成。

console.log(data.points);

if (!this.state.hasPressed) {
this.setState({points: data.points}, () => {
console.log(this.state.points);
});
console.log('in not hasPressed if');
}

引用react-native setState() API:

setState(updater, [callback])

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

关于node.js - 状态未正确设置 - React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45474261/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com