尝试更新状态时出现无限循环

时间:2019-05-29 00:41:04

标签: reactjs firebase firebase-authentication state

我使用firebase.auth()。onAuthStateChanged来更改我的状态,如果用户不为null,我想更新我的状态并在其中设置用户信息,但是当我尝试这样做时,我得到了一个无限循环,但是当我删除this.setState({userInfo:user})时,代码可以正常工作,位于我的代码下面:

class Test extends React.Component {

  state = {
    toDashboard: true,
    userInfo: null
  }


  render() {

    firebase.auth().onAuthStateChanged(user =>{
      if(!user){
        this.setState({toDashboard: false});
      }else{ //HERE is where I get the inifinite loop, if I delete the ELSE, it does not go into an infinite loop
        this.setState({userInfo: user});
      }
    })  

    if (this.state.toDashboard === false) {
      return <Redirect to='/auth/login' />
    }

    return (
      <>
        <Sidebar
          {...this.props}
          routes={routes}
          logo={{
            innerLink: "/admin/index",
            imgSrc: require("assets/img/brand/LogoMorado.png"),
            imgAlt: "Logo"
          }}
        />
        <div className="main-content" ref="mainContent">
          <AdminNavbar
            {...this.props}
            brandText={this.getBrandText(this.props.location.pathname)}
          />
          <Switch>{this.getRoutes(routes)}</Switch>
          <Container fluid>
            <AdminFooter />
          </Container>
        </div>
      </>
    );
  }
}

export default Test;

1 个答案:

答案 0 :(得分:2)

请勿在{{1​​}}中使用setState({})

它会导致render()

基本上,infinite loop代替了componentDidMount()

,您应该了解反应生命周期

https://reactjs.org/docs/react-component.html

render()