2017-08-03 42 views
1

我很困惑我从我的代码中得到什么。我有以下几种应该注销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

[]

+0

可能想在[docs](https://facebook.github.io/react/docs/react-component.html#setstate)上采取一些措施。 –

+0

TL; DR但我可能应该 – pudility

+0

啊@Val反正引用了相关部分。 –

回答

2

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'); 
} 

指反应天然setState() API:

的setState(更新器,[回调])

的setState()并不总是立即更新组件。它可能会批处理或延迟更新,直到更晚。这使得在调用setState()之后立即读取this.state 是一个潜在的错误。相反,请使用 componentDidUpdate或setState回调(setState(更新程序, 回调)),其中任何一个保证在应用更新 后触发。如果您需要根据以前的 状态设置状态,请阅读下面的updater参数。

+0

感谢您的答案!完美地工作。我将在6分钟内标记为正确。 – pudility

+0

不客气。很高兴它帮助=) – Val