简体   繁体   English

React - 检查 function 是否返回 true 但始终运行代码为 false

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

I bet this has something to do with asynchronicity.我敢打赌这与异步性有关。

Basically, I am checking if a string (an answer to a question) already exists, and if so, the page should just display a message, otherwise should add the new question to an array.基本上,我正在检查一个字符串(问题的答案)是否已经存在,如果存在,页面应该只显示一条消息,否则应该将新问题添加到数组中。

So in order to refactor the code, I have created a function called isDuplicateAnswer (yes, it's bound to the component).所以为了重构代码,我创建了一个名为 isDuplicateAnswer 的isDuplicateAnswer (是的,它绑定到组件)。 Here is the code for it:这是它的代码:

 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;
        }
      });
    }
  }

Based on this check the code will do the following:基于此检查,代码将执行以下操作:

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();
        })();
      });
    }

My problem is that if isDuplicateAnswer is false , as my log says "Everything is Ok", but when it returns true , the answer is created, resulting in an error due to the HTML key being not unique, even though the log from isDuplicateAnswer is displayed twice.我的问题是,如果isDuplicateAnswerfalse ,因为我的日志显示“一切正常”,但是当它返回true时,会创建答案,导致由于 HTML 键不是唯一的错误,即使来自isDuplicateAnswer的日志是显示两次。

Given that the other two checks in the guard are working correctly, what am I doing wrong here?鉴于警卫中的其他两项检查工作正常,我在这里做错了什么?

EDIT编辑

this is the state right before clicking on "Add Answer", which id is submitAnswer这是 state 就在点击“添加答案”之前,它的 id 是submitAnswer

在此处输入图像描述

There are multiple things wrong in your code.您的代码中有多个错误。 I will list the ones that are most obvious to me:我将列出对我来说最明显的那些:

1) Your isDuplicateAnswer() method will always return undefined which under if condition will always evaluate to false . 1)您的isDuplicateAnswer()方法将始终返回undefinedif条件下将始终评估为false That is why Something is wrong is never executed - it will never go to that block.这就是为什么永远不会执行Something is wrong的原因 - 它永远不会 go 到该块。

2) This one is linked to 1) above. 2)这个链接到上面的1) Basically map doesn't return a boolean , moreover you have to return the result of the function which you're not doing as well.基本上map不会返回boolean ,而且您必须返回 function 的结果,而您做得不好。 To fix this, use a method like some which does return a boolean:要解决此问题,请使用一些返回 boolean 的方法:

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) In the 2nd block, do not check for event.target.id === "submitAnswer" && this.state.answerTextTyped !== null twice. 3) 在第二个块中,不要检查event.target.id === "submitAnswer" && this.state.answerTextTyped !== null两次。 Just do:做就是了:

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.
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JavaScript 正则表达式测试函数在第一个 true 之后总是返回 false - JavaScript regex test function always returns false after the first true Function 返回 false 但我需要为什么返回 true 反应原生 - Function returns false but i need why return true react native React Query v3 useInfiniteQuery 返回 isLoading,isFetching 始终为 true,isFetchingNextPage 始终为 false - React Query v3 useInfiniteQuery returns isLoading, isFetching always true and isFetchingNextPage always false React JSX 检查异步 function 是否返回 true 或 false - React JSX check if async function return true or false isNaN 验证总是返回 TRUE 但在浏览器中它是 FALSE - isNaN validation always returns TRUE but in browser it is FALSE Ajax函数始终返回false - Ajax function always returns false JS函数始终返回False - JS Function Always Returns False 简单变量检查返回false,应为true - Simple variable check returns false, should be true await function 返回一个 promise 并且即使条件为假也返回 true | 反应功能组件 - await function returns a promise and returns true even if the condition is false | React Functional Component 如果返回始终为true并使用has()检查每个元素 - If returns always true and check each element with has()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM