在.then()内部调用函数会引发错误

Zainul Abideen

我正在尝试使用firebase执行某些任务,并在promise中调用某些函数而没有任何回调函数,这给了我一个错误。这是我的代码

onButtonPress = () => {
  const {email, password} = this.state
  this.setState({error: '', loading: true});

  firebase.auth().signInWithEmailAndPassword(email, password)
  .then(this.onAuthSuccess().bind(this))
  .catch(()=>{
    firebase.auth().createUserWithEmailAndPassword(email, password)
    .then(this.onAuthSuccess().bind(this))
    .catch(this.onAuthFailed().bind(this))
  })
}

  onAuthSuccess() {
    this.setState({
      email: '',
      password: '',
      error: '',
      loading: false
    })
  }

  onAuthFailed() {
    this.setState({
      error: "Authentication Failed",
      loading: false
    })
  }

这是我收到的错误消息

未定义不是对象(评估'_this.onAuthSuccess()。bind()')

雷克斯低

thisES6中处理上下文的3种方式

  1. 使用bind关键字
onAuthSuccess() {
    ...
}

firebase.auth()
    .then(this.onAuthSuccess.bind(this));
    .catch(this.onAuthFailed.bind(this));
}
  1. 使用箭头功能避免预绑定
onAuthSuccess = () => {
    ...
}

firebase.auth()
    .then(this.onAuthSuccess);
    .catch(this.onAuthFailed);
}
  1. 将方法绑定到构造函数中
constructor(props) {
    super(props);
    this.onAuthSuccess = this.onAuthSuccess.bind(this);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章