状态没有正确设置 – 反应原生

我从我的代码中得到的东西很困惑。 我有下面这应该注销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远程debugging器中,我得到了这个:

["114556548393525038426"]

in not hasPressed if

[]

setState是一个asynchronous调用。 你必须使用函数callback来等待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()并不总是立即更新组件。 它可能会批处理或推迟更新,直到更晚。 这使得在调用setState()之后读取this.state成为一个潜在的缺陷。 相反,使用componentDidUpdate或setStatecallback(setState(updater,callback)),其中任何一个保证在应用更新后触发。 如果您需要根据之前的状态设置状态,请阅读下面的updater参数。