【问题标题】:This.SetState is not workingThis.SetState 不起作用
【发布时间】:2017-12-09 20:10:28
【问题描述】:

我知道问题可能出在主登录功能中的功能上,但我无法抓住它。它返回此错误:

Unhandled Rejection (TypeError): undefined is not an object (evalating 'this.setState')

export default class Main extends React.Component{
  constructor(){
    super()
    this.state = {
      logged: null,
      name: "Felicia"
    };
  }
  login(e){
    const email = document.getElementById('txtEmail').value;
    const password = document.getElementById('txtPass').value;
    firebase.auth().signInWithEmailAndPassword(email, password);
    firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
          console.log("There is a user logged");
          console.log(user.email);
          this.setState({ name: firebase.auth.currentUser.displayName, logged: "true" })
        } else {
          console.log("No user Logged");
        }
      }).bind(this)

render(){
if(this.state.logged){
  return <Student name={this.state.name} />
} else {
  return (
    <div className="container">
    <div className="row">
    <div className="col-md-6 loginform">
    <input type="email" id="txtEmail" className="form-control" placeholder="email@email.co.uk" />
    <small id="emailHelp" className="form-text text-muted">Well never share your email with anyone else.</small>
    <input type="password" id="txtPass" className="form-control" placeholder="password"/>
    <button onClick={this.login} className="btn btn-primary">Login</button>
    </div>
    </div>
    </div>
  )
}
  }
}

你能帮我解决这个问题吗?

【问题讨论】:

  • 您是否尝试检查firebase.auth.currentUser 是否可用?
  • 代码中什么时候调用函数login()?
  • @Jay 如果 currentUser = null 则返回一个带有 onClick 函数的按钮
  • @Umesh 我尝试过使用if(firebase.auth.currentUser != null){ this.setState...},但它返回了同样的错误。
  • @PRvn 做一个console.log 并检查firebase.auth.currentUser.displayName 的值是什么,也请分享你调用函数的sn-p

标签: reactjs firebase authorization


【解决方案1】:

您没有将回调函数绑定到此。您应该将onAuthStateChanged的回调函数绑定到this,如

firebase.auth().onAuthStateChanged((function(user) {
     ...
}).bind(this))

【讨论】:

  • 他好像绑定了
  • @Jay 是的,但不是onAuthStateChanged的回调
  • 我刚刚添加了它,但它仍然返回相同的错误。
  • @PRvn 删除bind(this) 并尝试将function(user) { 转换为(user) =&gt; { 想看看它是否是绑定问题。
  • @Prakashsharma 成功了!非常感谢!您能否告诉我它是如何影响流量的,以便我以后避免这种情况?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-12
  • 1970-01-01
  • 2021-07-24
  • 2019-12-18
  • 2019-01-03
  • 2020-05-10
  • 2018-04-27
相关资源
最近更新 更多