Reactjs 在React中更新计数器的正确方法是什么

Reactjs 在React中更新计数器的正确方法是什么,reactjs,counter,setstate,Reactjs,Counter,Setstate,如何在状态中声明计数器,声明使用该计数器输出的其他变量,然后在onClick上更新计数器和所有其他变量?是因为setState是异步的吗?我刚开始做反应 const arr = Object.keys(questionAnswers).map(key => { return questionAnswers[key] }); this.current = 0; this.state = { current: this.current, questions: arr[thi

如何在状态中声明计数器,声明使用该计数器输出的其他变量,然后在onClick上更新计数器和所有其他变量?是因为setState是异步的吗?我刚开始做反应

const arr = Object.keys(questionAnswers).map(key => { return questionAnswers[key] });

this.current = 0;

this.state = {
    current: this.current,
    questions: arr[this.current].question,
    options: Object.keys(arr[this.current].options).map(key => { return arr[this.current].options[key]}),
    }
}
然后使用onClick函数进行更新:

nextQuestion = () => {
    this.current++
    this.setState({
    current: arr[this.current].question,
    options: arr[this.current].options
    });
}

可通过以下方式更新计数器:

setState((prevState) => {current: prevState.current + 1});

您可以将该状态称为this.state

this.state = {
  current: 0
  ...
}
无论何时更改状态,react都会触发组件的重新呈现,因此可以始终参考此状态。state

setState函数以批处理方式执行,并且其异步。在您的情况下,如果您想基于以前的状态更新变量,那么应该使用setState函数中的函数。这将提供同步更新

this.state = {
  current: 0
  ...
}
像这样的

this.setState((prevState, props) => ({
  current: prevState.current + 1
})); 

我的问题是如何使用current进行更新。例如,这似乎不起作用:`this.state={arr:arr,current:this.current,questions:arr[this.current].question,options:Object.keysarr[0].options.mapkey=>{return arr[0].options[key]},}}nextQuestion=>{this.setstateprovstateprovstate=>{current:prevState.current+1,question:prevState.arr[prevState+1].question}`