简体   繁体   English

如何在compoentWillMount ReactJS中使用setState()

[英]How to use setState() inside compoentWillMount ReactJS

I'm new to ReactJs. 我是ReactJs的新手。 I'm trying to create a firebase app using it. 我正在尝试使用它创建一个Firebase应用程序。 So in componentWillMount I'm checking if the user is logined or not and setting the state boolean value according to that 所以在componentWillMount中,我正在检查用户是否已登录,并根据该状态设置状态布尔值

  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. 但这表明setState()不是函数。

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 . 1)您需要将此代码移至componentDidMount componentWillMount is deprecated . 不推荐使用 componentWillMount Here's some more info as to why you should prefer componentDidMount 这是有关为什么您更喜欢componentDidMount的更多信息

2) Change your onAuthStateChanged callback to be an arrow function . 2)将您的onAuthStateChanged回调更改为箭头函数

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. this与反应成分无关。 Instead, try: 相反,请尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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