【问题标题】:React-native Firebase Auth setState in onAuthStateChanged got TypeError: this.setState is not a functiononAuthStateChanged 中的 React-native Firebase Auth setState 得到 TypeError: this.setState is not a function
【发布时间】:2019-07-02 19:12:03
【问题描述】:

我从 react-native 开始,并尝试使用 onAuthStateChanged 获取 firebase 用户数据。

我尝试过bindthis,但我仍然对此一无所知。

这是我的构造函数

constructor(props) {
    super(props);
    this.state = {
    isUid: '',
      isProvider:'',

      isPhoneNumber:'', 
    };

这是我在 componentDidMount 中的 onAuthStateChange

componentDidMount() { 
var user = firebase.auth().currentUser;
firebase.auth().onAuthStateChanged(function (user) {
    if (user) {
      user.providerData.forEach(function (profile) {

        this.setState({isProvider: profile.providerId}, console.log(isProvider)).bind(this); 
        this.setState({isPhoneNumber: profile.phoneNumber}, console.log(isPhoneNumber)).bind(this);
        this.setState({isUid: user.uid}, console.log(isUid)).bind(this);
});
} else {
  console.log('no user');
}
}

【问题讨论】:

    标签: javascript firebase react-native firebase-authentication


    【解决方案1】:

    由于您在onAuthStateChanged 回调中,this 与外部具有不同的含义。

    最简单的解决方法是使用粗箭头表示法,它保持this的含义:

    firebase.auth().onAuthStateChanged((user) => {
        if (user) {
          user.providerData.forEach(function (profile) {
            this.setState({isProvider: profile.providerId}, console.log(isProvider)).bind(this); 
            this.setState({isPhoneNumber: profile.phoneNumber}, console.log(isPhoneNumber)).bind(this);
            this.setState({isUid: user.uid}, console.log(isUid)).bind(this);
          });
        } else {
          console.log('no user');
        }
    }
    

    【讨论】:

    • 我收到了[Unhandled promise rejection: ReferenceError: Can't find variable: isProvider] 好像还没有设置状态。
    • 这是一个不同的错误。听起来isProvider 在您尝试使用它时不在范围内,但根据您共享的代码,我无法说出为什么会这样。最初的错误是由我在回答中解释的内容引起的,这就是为什么当您应用我指出的更改时该错误消失了。
    猜你喜欢
    • 1970-01-01
    • 2020-09-26
    • 2020-01-06
    • 2017-02-25
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多