简体   繁体   中英

How to use setState() inside compoentWillMount ReactJS

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

Few things:

1) You'll want to move this code to componentDidMount . componentWillMount is deprecated . Here's some more info as to why you should prefer componentDidMount

2) Change your onAuthStateChanged callback to be an 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
    })
  }
})

}

The problem comes from:

Firebase.auth().onAuthStateChanged(function(user){

this is not refferring to the react component. Instead, try:

Firebase.auth().onAuthStateChanged((user) => {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM