React +使用点击事件未定义的Firebase [英] React + Firebase undefined using click event

查看:149
本文介绍了React +使用点击事件未定义的Firebase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望这是一个快速的解决方案。基本上,我已经在一个子组件的几个元素上设置了onClick监听器,当它们被点击时,它从主要组件运行一个函数。一切正常,直到我们在调用firebase数据库时遇到了特定的行,在那里我得到了未定义的问题。

  getDataName(event){
var标题;
var that = this;
//从元素中获取数据名称属性
var grabIdentifier = event.target.getAttribute('data-name');
console.log(grabIdentifier); //打印巡航

//调用firebase
var greeting = database.ref('events / travel');
greeting.once('value')。then(function(snapshot){
console.log(grabIdentifier); //打印巡航

//将标题设置为
title = snapshot.val()。grabIdentifier;
console.log(title); //打印undefined=(

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

这里的想法是将状态设置为在firebase数据库的巡航键下存储为一个值的文本,难以置信!



这也可能有助于提及,如果我重写下面的行,并实际上放在这里,巡航的话,它的工作原理是奇怪的,见下面,

  title = snapshot.val()。cruise; 


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

  title = snapshot.val()[grabIdentifier] 

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


Hopefully this is a quick fix. Basically, I have set onClick listeners on a few elements of a child component, and when they are clicked, it runs a function from the main component. Everything works good, up until we hit a specific line in the call to the firebase database, where I get issues of undefined. I have included comments to the code below so you know exactly what's going on.

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

The idea here is to set the state to the text that is stored as a value under the key of "cruise" in the firebase db. Stumped!

It also might help to mention that if I rewrite the line below, and actually put the word, "cruise" there, it works...which is strange. See below,

 title = snapshot.val().cruise;

解决方案

You are trying to access the property called grabIdentifier you need to use bracket notation to access the property name that grabIdentifier is referencing

title = snapshot.val()[grabIdentifier]

for more information on property accessors see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

这篇关于React +使用点击事件未定义的Firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆