React +使用点击事件未定义的Firebase [英] React + Firebase undefined using click event
问题描述
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;
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屋!