How to use setState() inside compoentWillMount ReactJS

时间:2018-05-18 17:12:39

标签: javascript reactjs react-lifecycle

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 :(

2 个答案:

答案 0 :(得分:3)

少数事情:

1)您希望将此代码移至componentDidMountcomponentWillMountdeprecatedHere'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) => {