javascript - 为什么 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
。
解决方案
我不会使用 statefilledAll
因为它不应该重新渲染组件。
我会建议像 -
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");
}
}
推荐阅读
- sql-server - 具有多个数据集的 SSRS 性能
- security - 一次性 RSA 公钥
- c# - 正则表达式使用某些规则c#删除不必要的符号
- c++ - 如何知道创建对象时是否没有传入参数?
- java - 如何在 Thymeleaf 中使用 Dates.Format 和语言环境
- javascript - 从嵌套数组到对象的json转换
- ios - iOS Umbrella Framework - 代码设计问题
- ruby-on-rails - Ransack 和 find_by_sql
- java - 导入 javax.xml.parsers.ParserConfigurationException 无法解析
- javascript - 如何在使用 FileContentResult ActionResult 时了解客户端 ASP.NET MVC 中的文件下载状态?