2017-08-03 39 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