以下是我的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");
});
}
}
}
}