你好,我试图在用户登录firebase后执行登录道具,使用then(),我具有可以使用的用户变量,但是在这里不能使用_login函数:
onClickLogin = async () => {
if (this.state.email && this.state.password) {
firebase
.auth()
.signInWithEmailAndPassword(this.state.email, this.state.password)
.then(function (user) {
this._login(user)
})
.catch(function(error) {
if (error) {
alert(error)
}
})
} else {
alert('Veuillez remplir tous les champs')
}
}
_登录功能:
_login = async (user) => {
this.props.screenProps.isLoggedIn();
AsyncStorage.setItem('user', user.user.uid);
AsyncStorage.setItem('loggedInStatus', 'loggedIn');
}
我该怎么办?
尝试使用此功能:
onClickLogin = async () => {
if (this.state.email && this.state.password) {
firebase
.auth()
.signInWithEmailAndPassword(this.state.email, this.state.password)
.then(function (user) {
this._login(user)
}.bind(this)) // bind here
.catch(function(error) {
if (error) {
alert(error)
}
}.bind(this)); // bind here
} else {
alert('Veuillez remplir tous les champs')
}
}
为什么这两个绑定?
这没有用,因为axios内部的"this"
不同。 axios内部的"this"
是指axios对象,而不是您的react组件。因此,您可以使用.bind
解决此问题。
如先前的回答所述。回调中的this
绑定到您的firebase
上下文
为了将this
绑定到您的类,您可以使用bind function将this
回调内的then
绑定到作为this
函数的参数传递的bind
上你的课
为了避免将this
绑定到firebase
回调内部的then
上下文,您还可以使用箭头函数
.then((user) => {
this._login(user)
})