繁体   English   中英

反应本地firebase onAuthStateChanged

[英]react native firebase onAuthStateChanged

在以firebase为后端的我的react-native应用程序中,我有一个像这样的初始LoginScreen :( react-navigation的navigation函数将作为第一个参数传递的屏幕作为props.navigation.params.state传递给该屏幕的第二个参数)

class LoginScreen extends Component {

    constructor() {
        this.state = {
            currentUser: {},
            email: null,
            psw: null

...

async logIn(email, pass) {
  try {
      await firebaseApp.auth()
          .signInWithEmailAndPassword(email, pass)
  } catch (error) {
      alert(error.toString())
  }
}

listenForAuth() {
    const { navigation } = this.props
    this.unsubscribe = firebase.auth().onAuthStateChanged(user => {
        if (user) {
            this.setState({
                currentUser: {
                    id: user.uid
                }
            })
            navigation.navigate('MainApp', { currentUser: this.state.currentUser })
        } else {
            this.setState({
                loading: false
            })
        }
    })
}

componentWillMount() {
    this.listenForAuth()
}

render() {
    ...
    <LoginButton onPress={() => this.logIn(this.state.email,this.state.psw)
    ...

以及一个MainApp组件作为react-navigation tabNavigator,其“个人资料”屏幕如下所示:

class Profile extends Component {

    constructor(props) {
        super(props)
        const { currentUser } = this.props.navigation.state.params
        this.userRef = firebaseApp.database().ref( 'users/' + currentUser.id )
        this.postsRef = firebaseApp.database().ref( 'users/' + currentUser.id + '/myposts' )
        this.state = {
            currentUser: {},
            refreshing: false,
            postsDataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2,
            })
        }
    ...
    listenForUser(usersRef) {
       usersRef.on('value', snap => {
          this.setState({
            currentUser: {
              user: snap.val().user,
              photo: snap.val().photo,
              email: snap.val().email,
              id: snap.val().id
           }
         })
       })

  listenForPosts(postsRef) {
  postsRef.on('value', snap => {
    var posts = []
    snap.forEach( trip => {
      firebaseApp.database().ref( 'posts/' + posts.key ).on('value', child => {
          posts.push({
            title: child.val().title,
            own: child.val().own,
            _key: child.key
          })
       })
    })
    this.setState({
      postsDataSource: this.state.postsDataSource.cloneWithRows(posts)
    })
   })
  }

  componentDidMount() {
     this.listenForUser(this.userRef)
     this.listenForPosts(this.postsRef)
  }

  _onRefresh() {
     this.setState({ refreshing: true })
     this.listenForPosts(this.postsRef)
     this.setState({ refreshing: false })
  }
  ...
  render() {
    ...
    <Text>{this.state.currentUser.user}</Text>
    ...
    <ListView dataSource={this.state.postsDataSource} 
              refreshControl={
                 <RefreshControl
                    refreshing={this.state.refreshing}
                    onRefresh={this._onRefresh.bind(this)}
                 />}
    ...

启动应用程序时,侦听器首次感觉到用户的存在时,会导航到MainApp屏幕,但会出现警告,组件Profile的呈现功能中的{this.state.currentUser.user}未定义; 但是当我浏览tabBar时,我可以看到该用户名,但ListView为空。 如果刷新,则将检索firebase数据并填充ListView。

如果我注销并没有再次登录,则立即加载数据,不显示警告,并立即填充listview。

如果我退出并重新启动该应用程序,因为已经有一个登录用户,它将导航到MainApp屏幕,但是如果我注销并重新登录,一切正常,那么上面会出现相同的问题。

拜托,我怎么了? 有谁能够帮助我?

问题在于,当加载onAuthStateChanged时,currentUser仍为null。 但是,如果您等待一段时间并稍后再试(例如,相同的代码,但在另一个屏幕上),那么一切都会正常。 这就是为什么第二次尝试没有错误。

对于旁路,我使用了setInterval函数-它将自行执行,直到检索到currentUser对象为止

let renderAction = setInterval(() => {
        if ( firebase.auth().currentUser !== null ) {
            clearInterval(renderAction);
            let user = firebase.auth().currentUser;
            let uid = user.uid;
            this.setState({uid});
        } else {
          console.log('Wait for it');
        }
      }, 500);

另外,请注意,获取currentUser.uid并不是一个好主意,它应该首先等待currentUser,然后再获取其属性。 希望您没有等待太久,并且已经找到了解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM