Реагировать - проверить, возвращает ли функция true, но всегда запускает код для false - PullRequest
1 голос
/ 29 мая 2020

Готов поспорить, это как-то связано с асинхронностью.

В основном, я проверяю, существует ли уже строка (ответ на вопрос), и если да, то страница должна просто отображать сообщение, иначе должен добавить новый вопрос в массив.

Итак, чтобы реорганизовать код, я создал функцию с именем 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();
        })();
      });
    }

Моя проблема в том, что если isDuplicateAnswer равно false, то в моем журнале написано «Все в порядке», но когда он возвращает true, создается ответ, что приводит к ошибке из-за того, что ключ HTML не уникален, хотя журнал из isDuplicateAnswer отображается дважды.

Учитывая, что две другие проверки в страже работают правильно, что я здесь делаю не так?

РЕДАКТИРОВАТЬ

это состояние прямо перед нажатием на «Добавить ответ» ", идентификатор которого submitAnswer

enter image description here

1 Ответ

3 голосов
/ 29 мая 2020

В вашем коде несколько ошибок. Я перечислю наиболее очевидные для меня:

1) Ваш метод isDuplicateAnswer() всегда будет возвращать undefined, который при условии if всегда будет оцениваться как false. Вот почему Something is wrong никогда не выполняется - никогда не будет go для этого блока.

2) Этот блок связан с 1) выше. Обычно map не возвращает boolean, более того, вы должны вернуть результат функции, которую вы тоже не делаете. Чтобы исправить это, используйте метод типа some , который возвращает логическое значение:

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

...