React + Firebase undefined using click event

。_饼干妹妹 提交于 2019-12-24 08:36:34

问题


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;

回答1:


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



来源:https://stackoverflow.com/questions/39600061/react-firebase-undefined-using-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!