首页 > 解决方案 > onAuthStateChanged 中的 React-native Firebase Auth setState 得到 TypeError: this.setState is not a function

问题描述

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

我试着去做bind this,但我仍然不知道。

这是我的构造函数

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');
}
}

标签: javascriptfirebasereact-nativefirebase-authentication

解决方案


由于您在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');
    }
}

推荐阅读