更改reactjs组件状态字段的值(使用从firebase获取的数据)
问题描述:
我只是想从Firebase数据库中获取字符串并更新组件中的“eventName”字段,但我在执行此操作时遇到问题。 到目前为止我的代码:更改reactjs组件状态字段的值(使用从firebase获取的数据)
import React from 'react';
import {ref} from '../Firebase';
class EventDisplay extends React.Component {
constructor() {
super();
this.state = {
eventName: "No event Selected."
};
}
render() {
return (<div>
<h1>Name of Event: {this.state.eventName}</h1>
<h1>Date and Time: Dummy Name</h1>
<h1>Event Description: Dummy Name</h1>
</div>);
}
changeEventName(str) {
this.setState({eventName: str});
}
componentWillMount() {
const events = ref.child('events/event1/Title');
var param;
events.on('value', (function(snapshot) {
param = snapshot.val();
console.log(snapshot.val());
changeEventName(param);
})
);
console.log(param);
}
}
export default EventDisplay;
然而,changeEventName似乎不确定在哪里。另外“未定义”显示在我尝试记录参数的控制台中,但snapshot.val()具有所需的字符串。 感谢
答
changeEventName seems to be undefined where it is
当你调用changeEventName
你需要this
加前缀。
this.changeEventName
此外,由于你调用它的回调首先需要方法绑定,以保持的this
值内。有很多种方法可以做到这一点,最常见的是:
明确构造的内部:
this.changeEventName = this.changeEventName.bind(this)
或使用箭头功能:
events.on('value', ((snapshot) => { ... }));
Also "undefined" shows up in the console where I try to log param
这是因为events.on
是异步的,您需要将您的console.log
移到回调中。
答
尝试this.changeEventName
调用该函数;您需要这样做,因为该功能仅在该类的上下文中可用。
记录param
返回未定义,因为events.on
是一个异步函数。这意味着这个函数将执行任何它设计要做的事情(获取值),并且只有在准备好时才执行回调; param
仅在您提供的此回调方法中可用。
感谢您的解释;我用this.changeEventName和我得到了错误:这是null;幸运的是,我能够通过改变我的语法来解决这个问题(快照)=> {... – David
@David Ye,你首先需要绑定方法,检查更新的答案和解释为什么你需要它 – linasmnew