问题
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