无法读取 null 的属性“setState" [英] Cannot read property 'setState' of null
问题描述
我开始使用 ReactJS,我尝试使用 Firebase 作为数据库来收集我的数据.我现在卡住了 2 天,原因是这个错误:无法读取 null 的属性‘setState’"
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"
我可以从 Firebase 读取我的数据,但我无法显示它们......我真的不知道该怎么做:
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;
推荐答案
this
在 JavaScript 函数中的值因调用方式而异.当指定这样的回调函数时,外部作用域将不会被保留,因为它将从另一个上下文调用.查看这篇关于MDN 以获得更深入的解释.
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.
您可以使用bind
显式设置this
的值:
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
})
});
这篇关于无法读取 null 的属性“setState"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!