Cannot read property 'setState' of null

我怕爱的太早我们不能终老 提交于 2019-12-19 04:55:14

问题


im starting ReactJS and i try to use Firebase as a database to collect my data. Im stuck from 2 days now cause of this error : "Cannot read property 'setState' of null"

I can read my data from Firebase but i can't display them... I don't really know what to do :

import React from 'react';
import ProductList from '../Product/ProductList';
import Firebase from 'firebase';

class HomePage extends React.Component {
  constructor() {
    super();

    this.state = {
      productList: []
    }

    var firebaseRef = new Firebase('https://codehunt-one.firebaseio.com/');
    firebaseRef.child("products").on('value', function(snapshot) {
      var products = snapshot.val();
      console.log(products);

      this.setState({
        productList: products
      })
    });
  }

  render() {
    return (
      <section>
        <header>
          <img src="img/banner.jpeg" width="100%" />
        </header>

        <section>
          <section className="container">
              {this.state.productList
                ?
                <ProductList productList={this.state.productList}/>
                :
                null
              }

          </section>
        </section>
      </section>
    );
  }
}

export default HomePage;

回答1:


The value of this in a JavaScript function differs depending on how it was called. When specifying a callback function like this, the outer scope will not be preserved as it will be called from another context. Check out this article on MDN for a more in depth explanation.

You can explicitly set the value of this by using bind:

firebaseRef.child("products").on('value', function(snapshot) {
  var products = snapshot.val();

  this.setState({
    productList: products
  })
}.bind(this));

Or you can simply use an arrow function which uses lexical scoping. This basically means that the outer scope will be preserved as you seem to be expecting in this case:

firebaseRef.child("products").on('value', (snapshot) => {
  var products = snapshot.val();

  this.setState({
    productList: products
  })
});



回答2:


You can't use this.setState in the constructor because this is not available yet. Instead, move that piece of logic to componentWillMount and it should start working.

  constructor() {
    super();

    this.state = {
      productList: []
    }
  }

  componentWillMount() {
    var firebaseRef = new Firebase('https://codehunt-one.firebaseio.com/');
    firebaseRef.child("products").on('value', function(snapshot) {
      var products = snapshot.val();
      console.log(products);

      this.setState({
        productList: products
      })
    });
  }


来源:https://stackoverflow.com/questions/37929134/cannot-read-property-setstate-of-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!