NaN即使構成運算式的值都是有效數字,以下代碼也會回傳。我很困惑和沮喪xD。我的錯誤是什么?
private getAllData = (res: any) => {
this.setState({ priceBinance: res["binance"]["price"] })
this.setState({ volumeBinance: res["binance"]["volume"] })
this.setState({ highBinance: res["binance"]["high"] })
this.setState({ lowBinance: res["binance"]["low"] })
this.setState({ priceCrypto: res["crypto"]["price"] })
this.setState({ volumeCrypto: res["crypto"]["volume"] })
this.setState({ highCrypto: res["crypto"]["high"] })
this.setState({ lowCrypto: res["crypto"]["low"] })
this.setState({ priceKraken: res["kraken"]["price"] })
this.setState({ volumeKraken: res["kraken"]["volume"] })
this.setState({ highKraken: res["kraken"]["high"] })
this.setState({ lowKraken: res["kraken"]["low"] })
// THIS IS WHERE IT FAILS
this.setState({ priceAverage: (this.state.priceBinance! this.state.priceCrypto! this.state.priceKraken!) / 3.0 })
this.setState({ voulumeAverage: (this.state.volumeBinance! this.state.volumeCrypto! this.state.volumeKraken!) / 3.0 })
this.setState({ highAverage: (this.state.highBinance! this.state.highCrypto! this.state.highKraken!) / 3.0 })
this.setState({ lowAverage: (this.state.lowBinance! this.state.lowCrypto! this.state.lowKraken!) / 3.0 })
}
uj5u.com熱心網友回復:
setState是一個異步操作,這意味著一旦您為狀態設定了一個值,它就不需要立即更新狀態,而且您還可以使用 強制解開狀態值!,這NaN意味著狀態值尚未更新時您正在嘗試訪問狀態值,有兩種方法可以解決此問題:
狀態更新后呼叫回呼(不推薦,因為您必須為每個狀態值執行此操作)。
使用
res屬性直接獲取值并執行所需的操作。
this.setState({ priceAverage: (res["binance"]["price"] res["crypto"]["price"] res["kraken"]["price"]) / 3.0 })
uj5u.com熱心網友回復:
setState 是一個異步函式,因此您將獲得 NaN。嘗試使用 res 變數而不是使用 this.state 來設定每個狀態。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/416977.html
標籤:
