【问题标题】:Can't call setState on an unmounted component using firebase auth in react native无法在未安装的组件上调用 setState 在 react native 中使用 firebase auth
【发布时间】:2019-03-07 02:03:54
【问题描述】:

我在每次重新加载时都会出现这个警告,我不知道如何调试它,我在互联网上获取了一点,我发现的只是 this.mounted 的声明,并在它为 true 时使用 if 语句来 setState,我实现了它没有用,请有人看看我的代码,让我知道发生了什么,在 github 上使用 firebase 身份验证的人面临类似的问题,我仍在寻找那些被埋没的问题

export default class Login extends Component {
static navigationOptions = { header: null };
  constructor(props) {
     super(props)
     this.state = {
       currentUser: '',
       loading: false,
       error: null,
       UserInput: "",
       loggedIn: null,
       loggedOut: null,
       email: '', password: '',
     }
   }

   componentDidMount = () => {
     this.setState({ loading: true });
     firebase.auth().onAuthStateChanged((user) => {
       if(user) {
         const { navigate } = this.props.navigation;
         navigate('SponsorScreen')
         this.setState({ loggedIn: true, loggedOut: false, loading: false  });
       }
       else {
         this.setState({ loggedIn: false, loggedOut: true, loading: false });
       }
     });
    }

  onLogIn = () => {
    this.setState({ loading: true });
    const { email, password } = this.state;
    Keyboard.dismiss()
    firebase.auth().signInWithEmailAndPassword(email, password)
    .then(this.onSuccess.bind(this))
    .catch(() => {
      this.refs.modal.open();
      this.setState({ loading: false });
    })
  };

  onSignUp = () => {
    const { email, password } = this.state;
    this.setState({ loading: true });
    Keyboard.dismiss()
    firebase.auth().createUserWithEmailAndPassword(email, password)
    .then(this.onSuccess.bind(this))
    .catch(() => {
      this.refs.modal.open();
      this.setState({loading: false});
    })
  };

  onSuccess() {
    this.setState({
      email: '',
      password: '',
      loading: false,
      error: ''
    });
  };


render() {
  const { navigate } = this.props.navigation;
  return (

【问题讨论】:

标签: reactjs firebase react-native firebase-authentication


【解决方案1】:

在componentDidMount中,firebase.auth成功后,必须在setstate成功执行后使用setstate回调进行导航

componentDidMount = () => {
 this.setState({ loading: true });
 firebase.auth().onAuthStateChanged((user) => {
   if(user) {
     const { navigate } = this.props.navigation;

     this.setState({ loggedIn: true, loggedOut: false, loading: false  }, () => {
         navigate('SponsorScreen')
     });
   }
   else {
     this.setState({ loggedIn: false, loggedOut: true, loading: false });
   }
 });
}

【讨论】:

    猜你喜欢
    • 2019-01-26
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 2019-03-10
    • 2019-08-23
    • 2023-04-08
    • 1970-01-01
    • 2016-10-01
    相关资源
    最近更新 更多