错误:setState(..):需要更新状态变量的对象或返回状态变量对象的函数



它让我在其他部分this.state.incorrect + 1this.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)
}

在 react 中,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
});

您需要更新状态,因为您定义的状态是一个对象。并且您需要告诉要更新对象的哪个属性,如下所示。

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 给出了具有组件的 prev 状态的 prevState 对象。

this.setState(prevState => ({correct: prevState.correct + 1}))

最新更新