首页 > 解决方案 > 为什么 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

标签: javascriptreactjs

解决方案


我不会使用 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");
        }
    }


推荐阅读