I'm new to ReactJs. I'm trying to create a firebase app using it. So in componentWillMount I'm checking if the user is logined or not and setting the state boolean value according to that
componentWillMount() {
var config = {...};
Firebase.initializeApp(config)
Firebase.auth().onAuthStateChanged(function(user){
if(user){
console.log("User logined");
this.setState({
isLogined : true
})
}else{
console.log("User isn't logined");
this.setState({
isLogined : false
})
}
})
}
But it's showing setState() is not a function.
index.js:2178 TypeError: this.setState is not a function
at Object.next (App.js:31)
at index.cjs.js:1353
at index.cjs.js:1457
Need Help :(
答案 0 :(得分:3)
少数事情:
1)您希望将此代码移至componentDidMount
。
componentWillMount
是deprecated。 Here's更多信息,说明为什么你应该更喜欢componentDidMount
2)将您的onAuthStateChanged
回调更改为arrow function。
componentDidMount() {
var config = {...};
Firebase.initializeApp(config)
Firebase.auth().onAuthStateChanged((user) => {
if(user){
console.log("User logined");
this.setState({
isLogined : true
})
}else{
console.log("User isn't logined");
this.setState({
isLogined : false
})
}
})
}
答案 1 :(得分:2)
问题来自:
Firebase.auth().onAuthStateChanged(function(user){
this
不会对反应组件进行审核。相反,尝试:
Firebase.auth().onAuthStateChanged((user) => {