[英]Error: setState(...): takes an object of state variables to update or a function which returns an object of state variables
它在其他部分給了我錯誤this.state.incorrect + 1
和this.state.correct + 1
我已經看到了這個但沒有解決我的問題React Native: setState(...): 需要一個狀態變量對象來更新或一個返回狀態變量對象的函數
if (choice == this.state.dataset[this.state.current].correct) {
this.setState(this.state.correct + 1)
} else {
this.setState(this.state.incorrect + 1)
}
您需要更新狀態,因為您定義的狀態是一個對象。 並且您需要告訴您正在更新對象的哪個屬性,如下所示。
if (choice == this.state.dataset[this.state.current].correct) {
this.setState({correct: this.state.correct + 1})
} else {
this.setState({incorrect: this.state.incorrect + 1})
}
文檔參考
更新
正如@titus 以正確的方式更新評論的方式如下所示,因為 react 給出了 prevState 對象,該對象具有組件的 prev 狀態。
this.setState(prevState => ({correct: prevState.correct + 1}))
在反應中setState
接受一個對象或一個異步函數。 你沒有使用它們。 在您的情況下,如果您需要更新需要使用的狀態值
this.setState({correct: this.state.correct + 1});
使用這種方式設置狀態值時也要小心,因為setState
是異步操作,您可能無法保證立即獲得狀態變量的值。 如果你想使用setState()
的值,那么使用setState
的異步回調
this.setState({correct: this.state.correct + 1}, function() {
// you get the new value of state immediately at this callback
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.