为什么 this.setState 仅在 react js 应用程序中的两个提交事件后才起作用?



以下是我的handleSubmit函数,当提交充满问题的表单时会触发该函数。问题是,即使回答了所有21个问题,filledAll也不会更改为true。但是当我第二次单击提交时,filledAll设置为true

handleSubmit(event){
event.preventDefault();
let sum = 0;
this.state.score.forEach(function(value, index){
if (value !== undefined) {
sum += Number(value);
}
});
console.log(sum);
if (this.state.score.length === 0) {
this.setState({filledAll: false});
console.log('Scroll to question 1')
this.doScrolling("#question-1", 1000)
} else {
for (let i = 1; i <= 21; i++) {
console.log('Score of all 21 questions', this.state.score[i]);
// wherever the score is undefined
if (this.state.score[i] === undefined) {
console.log('if score is undefined, set filledAll to false.')
this.setState({filledAll: false});
console.log('Scroll to #question-' + i)
this.doScrolling("#question-" + i, 1000)
break;
}
else {
this.setState({filledAll: true});
console.log('else block', this.state.filledAll);
localStorage.setItem('total', sum)
// window.location.replace("/index");
}
}
}
}

我正在使用filledAll,所以我可以知道何时回答所有问题,并在true时重定向到另一个页面。

我不会对filledAll使用状态,因为它不应该重新渲染组件。

我会建议类似的东西——

handleSubmit(event){
event.preventDefault();
let sum = 0;
let filledAll = true;
this.state.score.forEach(function(value, index){
if (value !== undefined) {
sum += Number(value);
}
});
console.log(sum);
if (this.state.score.length === 0) {
console.log('Scroll to question 1')
this.doScrolling("#question-1", 1000)
} else {
for (let i = 1; i <= 21 && filledAll; i++) {
console.log('Score of all 21 questions', this.state.score[i]);
// wherever the score is undefined
if (this.state.score[i] === undefined) {
console.log('if score is undefined, set filledAll to false.')
filledAll = false;
console.log('Scroll to #question-' + i)
this.doScrolling("#question-" + i, 1000)
break;
}
}
}

if (filledAll) {
console.log('filled all');
localStorage.setItem('total', sum)
window.location.replace("/index");
}
}

this.setState是一个异步函数。因此,状态的更新最终只会发生。在您的情况下,this.setState 下面的代码将在调用 this.setState 后立即运行。通过将代码移动到this.setState下面的回调即可完成工作。

handleSubmit(event){
event.preventDefault();
let sum = 0;
this.state.score.forEach(function(value, index){
if (value !== undefined) {
sum += Number(value);
}
});
console.log(sum);
if (this.state.score.length === 0) {
this.setState({filledAll: false}, () => {
console.log('Scroll to question 1')
this.doScrolling("#question-1", 1000)
});
} else {
for (let i = 1; i <= 21; i++) {
console.log('Score of all 21 questions', this.state.score[i]);
// wherever the score is undefined
if (this.state.score[i] === undefined) {
console.log('if score is undefined, set filledAll to false.')
this.setState({filledAll: false}, () => {
console.log('Scroll to #question-' + i)
this.doScrolling("#question-" + i, 1000)
});
break;
}
else {
this.setState({filledAll: true}, () => {
console.log('else block', this.state.filledAll);
localStorage.setItem('total', sum)
// window.location.replace("/index");
});
}
}
}
}

最新更新