【问题标题】:React + Firebase undefined using click event使用点击事件未定义 React + Firebase
【发布时间】:2017-01-28 17:31:59
【问题描述】:

希望这是一个快速修复。基本上,我在子组件的一些元素上设置了 onClick 侦听器,当它们被单击时,它会从主组件运行一个函数。一切正常,直到我们在调用 firebase 数据库时遇到特定行,我遇到了未定义的问题。我已将 cmets 包含在下面的代码中,以便您确切知道发生了什么。

getDataName(event) {
    var title;
    var that = this;
    // Grabs data name attribute from element clicked
    var grabIdentifier = event.target.getAttribute('data-name');
    console.log(grabIdentifier); // prints "cruise"

    // Call to firebase
    var greeting = database.ref('events/travel');
      greeting.once('value').then(function(snapshot) {
      console.log(grabIdentifier); // prints "cruise"

      // Set title to value of the "cruise" key.
      title = snapshot.val().grabIdentifier;
      console.log(title); // prints "undefined" =(

      that.setState({
         greeting : title
       });
    });
  }

这里的想法是将状态设置为作为值存储在 firebase db 中“cruise”键下的值。难倒!

如果我改写下面的行,并且实际上把“巡航”这个词放在那里,它也会起作用……这很奇怪。见下文,

 title = snapshot.val().cruise;

【问题讨论】:

    标签: javascript reactjs firebase firebase-realtime-database


    【解决方案1】:

    您正在尝试访问名为 grabIdentifier 的属性,您需要使用括号表示法来访问 grabIdentifier 引用的属性名称

    title = snapshot.val()[grabIdentifier]
    

    有关属性访问器的更多信息,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

    【讨论】:

    • 你先生是个英雄。感谢您提供简单的解决方案。
    • 没问题!乐于助人:)
    猜你喜欢
    • 2018-05-09
    • 2015-08-09
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 2019-04-26
    • 2019-02-26
    • 2017-05-01
    • 1970-01-01
    相关资源
    最近更新 更多