反应-检查函数是否返回true,但始终运行false的代码

问题描述 投票:1回答:2

我敢打赌,这与异步性有关。

[基本上,我正在检查是否已存在字符串(问题的答案),如果存在,则页面应仅显示一条消息,否则应将新问题添加到数组中。

因此,为了重构代码,我创建了一个名为isDuplicateAnswer的函数(是的,它已绑定到组件)。这是它的代码:

 isDuplicateAnswer() {
    if (this.state.answersToCurrentQuestion.length > 0) {
      this.state.answersToCurrentQuestion.map(answer => {
        if (this.state.answerTextTyped === answer.text) {
          console.log("true"); // executed twice but then adds it to the array (not supposed to)
          return true;
        }
      });
    }
  }

基于此检查,代码将执行以下操作:

if (
      event.target.id === "submitAnswer" &&
      this.state.answerTextTyped !== null &&
      this.isDuplicateAnswer()
    ) {
      console.log("Something is wrong"); // This line is never executed (no log, no message)
      return this.props.handleMessage(
        "There is already another answer with this text. Please add a different one."
      );
    } else if (
      event.target.id === "submitAnswer" &&
      this.state.answerTextTyped !== null &&
      !this.isDuplicateAnswer()
    ) {
      console.log("Everything OK"); // not displayed but rest of the code goes through (answer added)
      this.setState({ answerText: this.state.answerTextTyped }, () => {
        (() => {
          let answersToCurrentQuestion = [
            ...this.state.answersToCurrentQuestion,
          ];
          answersToCurrentQuestion.push({
            text: this.state.answerText,
            isCorrect: this.state.isCorrectAnswer,
          });
          this.setState({ answersToCurrentQuestion });
          if (this.state.isCorrectAnswer === true) {
            this.incrementCorrectAnswers();
          }
        })();
        (() => {
          this.props.handleMessage("");
          this.setState({
            isValid: true,
            isCorrectAnswer: false,
            answerTextTyped: null,
          });
          this.refreshAnswerTypedForm();
          this.getAnswerTypedForm();
        })();
      });
    }

[我的问题是,如果isDuplicateAnswerfalse,正如我的日志中所说的“一切都很好”,但是当它返回true时,将创建答案,由于HTML键不是唯一的,因此导致错误,即使isDuplicateAnswer中的日志显示两次。

鉴于后卫中的其他两项检查均正常工作,我在这里做错了什么?

编辑

这是单击“添加答案”之前的状态,其ID为submitAnswer

enter image description here

javascript reactjs if-statement jsx boolean-logic
2个回答
1
投票

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.