我正在尝试使用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()')
this
ES6中处理上下文的3种方式。
- 使用
bind
关键字
onAuthSuccess() {
...
}
firebase.auth()
.then(this.onAuthSuccess.bind(this));
.catch(this.onAuthFailed.bind(this));
}
- 使用箭头功能避免预绑定
onAuthSuccess = () => {
...
}
firebase.auth()
.then(this.onAuthSuccess);
.catch(this.onAuthFailed);
}
- 将方法绑定到构造函数中
constructor(props) {
super(props);
this.onAuthSuccess = this.onAuthSuccess.bind(this);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句