尝试使用 setState 时出现以下错误:
Uncaught TypeError: Cannot read property 'setState' of null
我不知道我哪里出错了,有人可以指出我正确的方向吗?这是我的代码:
export default React.createClass({
getInitialState: function () {
return {
name: '',
address: '',
phone: '',
email: '',
}
},
componentWillMount(){
this.getUserDetails();
},
getUserDetails: function(){
var personID = 'ABC123';
if(personID.length > 0){
new Firebase('https://xxxxxxxxxx.firebaseio.com/users/' + personID).on('value', function(snap) {
this.setState({
name: snap.val().Name + " " +snap.val().Surname
});
});
}
},
render() {
return ( ... );
}
});
就像上面人们所说的那样,如果您只是将其编辑为箭头函数,它将this
的上下文从Firebase更改为外部范围 - 这是组件。
new Firebase('https://xxxxxxxxxx.firebaseio.com/users/' + personID).on('value', (snap) => {
this.setState({
name: snap.val().Name + " " +snap.val().Surname
});
});
发生这种情况是因为它的上下文不再是组件。您需要此组件。检查我如何抓取这个组件。
export default React.createClass({
getInitialState: function () {
return {
name: '',
address: '',
phone: '',
email: '',
}
},
componentWillMount(){
this.getUserDetails();
},
getUserDetails: function(){
var that = this
var personID = 'ABC123';
if(personID.length > 0){
new Firebase('https://xxxxxxxxxx.firebaseio.com/users/' + personID).on('value', function(snap) {
that.setState({
name: snap.val().Name + " " +snap.val().Surname
});
});
}
},
render() {
return ( ... );
}
});