为什么在Firebase查询创建数组后未调用setState?为什么setState不用数组更新状态?

时间:2018-06-11 10:05:20

标签: javascript reactjs firebase firebase-realtime-database chart.js

我正在使用Chart.js,React和Firebase制作实时图表。我希望setState更新chartData.labelchartData.datasets.data状态,其中包含两个我使用.on()方法从Firebase引入的数组。创建数组并在调用setState之前将它们记录到控制台,但是setState无法调用。我知道我可以使用.once()方法的一个承诺,但我需要像这位先生那样听取变化:How do I ensure setState is called after the Firebase query populates array?。我累了使用snapshot.exists(),但它没有给我我想要的结果。

如何使用这两个数组更新状态:yArraytimeArray

 class App extends Component {
    constructor(){
    super();
    this.state = {
      chartData:{
        labels: [1,2,3],
        datasets:[
           {
            label: 'Population',
            data: [1,2,3]
             }
          ]
      }      
    }
  }
   componentDidMount(){

   this.getChartData();
  }

   getChartData(){

    let currentComponent = this;

    let firebaseRef = app.database();;
    let sensorRef = firebaseRef.ref("data");

    sensorRef.limitToLast(20).on("value", (snapshot) => {
    var yArray = [];
    var timeArray = [];

    snapshot.forEach(snapshot => {

     var y = snapshot.val().y;
     var x = snapshot.val().time;

     yArray.push(y);
    timeArray.push(x);
   })

 console.log(yArray);    // Why do these arrays log in the console, while 
                         // this.state does not change? 
 console.log(timeArray); // Why would console.log(this.state) still show 
                         // [1,2,3] for chartData.label and 
                         // chartData.datasets.data while 
                         // console.log(timeArray) logs the arrays??

    currentComponent.setState({
      chartData:{
       labels: timeArray,
       datasets:[{
       label: 'Population',
       data: yArray
        }]
       }
    })
   })
 }

0 个答案:

没有答案