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

标签 node.js react-native

我对从代码中得到的内容感到非常困惑。我有以下内容应该注销 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/

相关文章:

javascript - 在javascript中处理TCP数据

node.js - 错误!此包已标记为私有(private)

node.js - NVM 全局模块文件夹

javascript - 打破 setTimeout 循环

mysql - Nodejs和mysql重复问题

javascript - 如何在 React Native 中绘制图片?

reactjs - React Native——可以在 return() 中使用 console.log 吗?

reactjs - 抽屉未覆盖 react 导航中的标题

react-native - 如何使 Horizo​​ntal SectionList RIGHT to LEFT Scroll react-native

javascript - 如何在 React Native 中滚动到 View ?