2017-05-17 210 views
0

我想从火力传递returend参数的状态PARAM,但我发现这个错误的特性“的setState”:阵营+火力地堡:类型错误:无法读取空

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 
    }); 
}); 
    } 

我该如何解决?由于

UPDATE Mayank Shukla'comment后,我能够做正确传递 “快照”:

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 
    }); 
}); 
    } 

但现在我有这样的问题:

​​

关于此功能:

_getCalendarsList(){ 
    var d = new Date(); 

    return this.state.calendars.map((calend) => { 
    return (
     <Calendar 
     {...calend} 
     key={d.getTime()} /> 

    ) 
    }); 
    } 
+1

这是一个绑定问题,使用箭头函数:'urlRef.once(“value”,(snapshot)=> {'解决问题。 –

+0

可能重复的[不能setState内部回调](http://stackoverflow.com/questions/43275845/cannot-setstate-inside-callback) –

+0

@MayankShukla确定它的工作原理,但现在我有这个问题:“TypeError:this.state .calendars.map不是一个函数“快照可能不是一个迭代? –

回答

0

要在任何变量使用map,该变量需要有一个array,你是取在componentDidMount方法的数据,将最初的渲染之后被调用,所以在状态确认的初始值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()} 
      /> 

     ) 
    }); 
} 
+0

是的初始值,在构造函数中我已经有“this.state = { 日历:[], GAPI:空 }” –

+0

这意味着,您所获取的数据是不一个数组,做'console.log(快照)'一旦你得到响应和检查,同时显示结果我。 –

+0

返回一种树:V {A:O,V:U,g:rc}。我做了一个截图:[link](https://ibb.co/h9VhmQ) –