[英]Cannot find property set in componentWillMount
I know I'm missing something basic here and if someone could help I would really appreciate it. 我知道我错过了一些基本的东西,如果有人可以提供帮助,我会非常感激。 This code gives me a warning: "Cannot read property 'setState' of null."
这段代码给了我一个警告:“无法读取null的属性'setState'。”
constructor(props) {
super(props);
this.state = {
foundUser: false
}
}
componentWillMount() {
var requestEmail = this.props.email
new Firebase(url)
.orderByChild('email')
.startAt(requestEmail)
.endAt(requestEmail)
.once('value', function (snap) {
var foundUser = snap.val();
if (foundUser) {
this.setState({found: true})
} else {
this.setState({foundUser: false})
}
});
},
render: function () {
if (this.state.foundUser === false) {
//render a scene here ...
}
return ( ....
You're missing the initial state of the component, try to add following function to your component 您缺少组件的初始状态,请尝试向组件添加以下功能
getInitialState: function() {
return {
foundUser: false
};
}
You need to make sure you have the correct context of the component when you use this
: 你需要确保你有分量的正确的上下文当您使用
this
:
componentWillMount() {
var self = this;
var requestEmail = this.props.email
new Firebase(url)
.orderByChild('email')
.startAt(requestEmail)
.endAt(requestEmail)
.once('value', function (snap) {
var foundUser = snap.val();
if (foundUser) {
self.setState({found: true})
} else {
self.setState({foundUser: false})
}
});
},
Save a reference to this
in a variable, or you could use .bind
, or even better es6 arrow function, since it looks like you are using es6. 在变量中保存
this
的引用,或者您可以使用.bind
,甚至更好的es6箭头函数,因为它看起来像您正在使用es6。
new Firebase(url)
.orderByChild('email')
.startAt(requestEmail)
.endAt(requestEmail)
.once('value', (snap) => {
var foundUser = snap.val();
if (foundUser) {
this.setState({found: true})
} else {
this.setState({foundUser: false})
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.