我正在使用setState来增加我所做的测验的分数。我使用回调方法,所以我没有改变数据但它只显示了2分。我不知道我做错了什么…每当表单提交时,我调用calculateScore函数onSubmit={this.calculateScore}.
if(this.state.question1 === '1996') {
this.setState((curr)=>{
return {score: curr.score++}
})
}
if(this.state.question2 === 'NWA') {
this.setState((curr)=>{
return {score: curr.score++}
})
}
if(this.state.question3 === 'bad-boy') {
this.setState((curr)=>{
return {score: curr.score++}
})
}
if(this.state.question4 === 'big-l') {
this.setState((curr)=>{
return {score: curr.score++}
})
}
if(this.state.question5 === 'snoop-dogg') {
this.setState((curr)=>{
return {score: curr.score++}
})
}
console.log(this.state);
console.log('calculating')
}
您正在使用后缀操作符value++
而不是前缀++value
。尝试使用前缀操作符,应该可以正常工作,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment