【问题标题】:Why is the condition in this callback always returns false?为什么这个回调中的条件总是返回false?
【发布时间】:2021-03-31 05:13:42
【问题描述】:

我有一个基于 Vue 的家庭 SPA。其中一个组件由v-if="isDisplayed"驱动。

这个isDisplayed是通过监听一个MQTT主题(见脚注)设置的,接收到的新消息由以下函数处理(我特别使用'hello'而不是false来确保切换到那里)。感兴趣的topicdisplay_school_edt

mqttMessage(topic, message) {
      console.log(`App.vue received topic ${topic} with payload '${message}'`)
      if (topic === "dash/reload") {
        window.location.href = window.location.href
        document.location.reload(true);
      }
      if (topic === "dash/darkmode") {
        this.nightmode = JSON.parse(message) ? "night" : "day";
      }
      // this is the part I have problems with, I left everything for completness
      if (topic === "display_school_edt") {
        console.log(`edt display received: '${message}'`);
        if (message === 'on') {
          this.isEdtDisplayed = true
        } else {
          this.isEdtDisplayed = 'hello'
        }
        // I initially went for the ternary below - same results
        // message === "on" ? this.isEdtDisplayed = true : this.isEdtDisplayed = 'hello';
        console.log(`new edt display: ${this.isEdtDisplayed}`);
      }
    }

当我发布到受监控主题display_school_edt(两次:消息是on,另一次是off)时,我在控制台上得到了以下信息:

也就是说,无论是收到on还是off,条件始终为假。

我的代码明显有问题,但我越看越好看。


脚注:事实上,特定协议并不重要(它是一种经常与 IoT 一起使用的总线),您可以假设 mqttMessage() 以某种方式使用参数 topicmessage 执行都是字符串。

【问题讨论】:

  • 关于脚注:您能否调试并绝对确定message 是一个字符串?喜欢console.log(typeof message)。我认为这是问题所在,您应该这样做 if (message+'' === 'on') -- 将 message 转换为字符串。
  • @trincot:啊,你是对的。这实际上很奇怪(因此不符合 MQTT 协议 BTW):object。当我console.log(message) 我看到Uint8Array(3) [111, 102, 102]。我正在阅读有关developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 的信息。编辑; .toString() 是解决方案。您介意引导一个答案,以便我可以使用参考文献对其进行编辑并接受它吗?谢谢!

标签: javascript if-statement conditional-statements conditional-operator


【解决方案1】:

如果message 是字符串类型,这确实是出乎意料的。但是,它可能不是,并且只有在您输出message 时,您实际上将其强制转换为字符串。因此,如果您从之前的输出中看到它强制转换为“否”,那么在 if 条件下您应该执行相同的操作,并强制转换为字符串:

if (message+'' === 'no')

注意:这将调用 message.toString(),就像您在模板文字中将其引用为 ${message} 时一样。

【讨论】:

  • 我建议写 String(message)message.toString() 而不是通过连接强制。
  • @Bergi:当我在一个月后回到这段代码并开始怀疑我的意思时,我实际上使用了.toString() 来清楚起见。
猜你喜欢
  • 2019-05-20
  • 1970-01-01
  • 1970-01-01
  • 2016-09-13
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多