TypeError:如果“ false”无法按预期工作

问题描述

我正在使用React.js进行PWA测验应用程序,并且遇到了以下问题:

我可以获得只有一个答案,而有多个答案的问题对象。

在只有一种可能的答案的情况下,我想强迫用户只有一种可能性。

为此,我做了以下算法:

  clickOnChoice = (key) => {
    if (this.state && this.state.correctAnswers) {
      let newChoices = INITIAL_CHOICES; // {}
      if (this.state.multiChoice) {
        console.log("this.state.multiChoice:",this.state.multiChoice); // this.state.multiChoice: false ???
        newChoices = JSON.parse(JSON.stringify(this.state.choices)); // {answer_b: 1}
      }
      newChoices[key] = 1 - (newChoices[key] | 0); // {answer_b: 1,answer_a: 1}
      this.setState({
        choices: newChoices
      },this.updateNextButtonState);
    }
  }

但是执行似乎忽略了条件if (this.state.multiChoice)

我想念什么?

gif

也许我需要一杯咖啡...☕

无论如何,先谢谢!

解决方法

您很有可能尝试检查字符串'false'而不是实际的布尔值。

您可以检查字符串是否为预期的布尔值if (this.state.multiChoice === 'true'),或将state属性的值更改为true ||。错误