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

09-28 00:52