。nn()中使用this.props的本地响应调用异步函数

问题描述 投票:3回答:2

你好,我试图在用户登录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');
}

我该怎么办?

firebase react-native asynchronous
2个回答
3
投票

尝试使用此功能:

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解决此问题。


1
投票

如先前的回答所述。回调中的this绑定到您的firebase上下文

为了将this绑定到您的类,您可以使用bind functionthis回调内的then绑定到作为this函数的参数传递的bind上你的课

为了避免将this绑定到firebase回调内部的then上下文,您还可以使用箭头函数

.then((user) => {
  this._login(user)
})
© www.soinside.com 2019 - 2024. All rights reserved.