我试图将来自firebase的returend参数传递给状态参数,但我收到此错误:
App.js:43 Uncaught TypeError: Cannot read property 'setState' of null
我想传递"快照"数组到"日历"然后检索日历值,例如" 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()} />
)
});
}
答案 0 :(得分:0)
要对任何变量使用map
,该变量必须是array
,您在componentDidMount
方法中获取数据,它将在初始渲染后调用,因此make确保状态calendars
的初始值应为[]
,如下所示:
constructor(){
super();
this.state = {
calendars: [],
....
}
}
或者在使用map
之前进行检查,如果不是array
然后是return null
,请执行以下操作:
_getCalendarsList(){
if(!Array.isArray(this.state.calendars))
return null;
var d = new Date();
return this.state.calendars.map((calend) => {
return (
<Calendar
{...calend}
key={d.getTime()}
/>
)
});
}