React - 检查函数 returns 是否为 true 但始终为 false 运行代码

React - Check if function returns true but always runs code for false

我打赌这与异步性有关。

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

所以为了重构代码,我创建了一个名为 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,正如我的日志所说 "Everything is Ok",但是当它 returns true 时,就会创建答案,由于 HTML 键不唯一而导致错误,即使来自 isDuplicateAnswer 的日志显示两次。

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

编辑

这是点击"Add Answer"之前的状态,id为submitAnswer

您的代码中有多处错误。我将列出对我来说最明显的那些:

1) 您的 isDuplicateAnswer() 方法将始终 return undefined,在 if 条件下将始终计算为 false。这就是为什么 Something is wrong 永远不会被执行——它永远不会去那个块。

2) 这个链接到上面的 1)。基本上 map 不会 return 和 boolean,而且你必须 return 你没有做的函数的结果。要解决此问题,请使用 some 之类的方法,该方法执行 return 布尔值:

isDuplicateAnswer() {
       return this.state.answersToCurrentQuestion.some(answer => this.state.answerTextTyped === answer.text);
        // If we find that answer already exists, some will return true, otherwise false.
  }

3) 在第二个块中,不要检查 event.target.id === "submitAnswer" && this.state.answerTextTyped !== null 两次。只要做:

if (event.target.id === "submitAnswer" && this.state.answerTextTyped !== null) {
    if (isDuplicateAnswer()) {
        console.log("Something is wrong");
        return this.props.handleMessage("There is already another answer with this text. Please add a different one.");
        // No setState call to change anything.
    } else {
        // Call setState and add your answer.
    }