【发布时间】:2017-05-17 07:49:05
【问题描述】:
我正在尝试将返回参数从 firebase 传递给状态参数,但我收到了这个错误:
App.js:43 Uncaught TypeError: Cannot read property 'setState' of null
我想将“snapshot”数组传递给“calendars”,然后检索“calendars.summary”或“calendars.date”之类的日历值(我知道该怎么做,但问题是我做不到将快照分配给日历)。
componentDidMount() {
//setInterval(() => start(this.state.gapi,true), 30000);
var rootRef = firebase.database().ref();
var urlRef = rootRef.child("testCalendar/calendars");
urlRef.once("value", function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key+": "+child.child("summary").val());
});
this.setState({
calendars: snapshot
});
});
}
我该如何解决?谢谢
更新 在 Mayank Shukla 发表评论后,我可以通过以下方式正确传递“快照”:
componentDidMount() {
//setInterval(() => start(this.state.gapi,true), 30000);
var rootRef = firebase.database().ref();
var urlRef = rootRef.child("testCalendar/calendars");
urlRef.once("value", function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key+": "+child.child("summary").val());
});
this.setState({
calendars: snapshot
});
}.bind(this));
}
或
componentDidMount() {
//setInterval(() => start(this.state.gapi,true), 30000);
var rootRef = firebase.database().ref();
var urlRef = rootRef.child("testCalendar/calendars");
urlRef.once("value", (snapshot) => {
snapshot.forEach(function(child) {
console.log(child.key+": "+child.child("summary").val());
});
this.setState({
calendars: snapshot
});
});
}
但现在我有这个问题:
Uncaught TypeError: this.state.calendars.map is not a function
关于这个功能:
_getCalendarsList(){
var d = new Date();
return this.state.calendars.map((calend) => {
return (
<Calendar
{...calend}
key={d.getTime()} />
)
});
}
【问题讨论】:
-
绑定问题,使用箭头函数:
urlRef.once("value", (snapshot) => {解决问题。 -
@MayankShukla 好的,但现在我遇到了这个问题:“TypeError: this.state.calendars.map is not a function”也许是因为快照不是可迭代的??
-
_getCalendarsList(){ var d = new Date(); return this.state.calendars.map((calend) => { return (
) }); } -
this.state.calendar 应该是一个数组来映射它,console.log(this.state.calendar) 在函数中,看看你得到了什么对象
标签: javascript reactjs firebase firebase-realtime-database calendar