将用户数据从屏幕传递到屏幕 - React Native

时间:2021-03-10 20:54:08

标签: javascript firebase react-native google-cloud-firestore firebase-authentication

我是 React Native 的新手,我正在尝试将数据 user.uid 从 LoginAdult 屏幕推送并获取(和打印)到 HomeParent 屏幕。在 HomeParent 屏幕中,我想使用它(将它传递给其他屏幕)。如果有人帮助我,将不胜感激!

登录Adult.js:

class LoginAdult extends React.Component {
  constructor(props){
    super(props)
    this.state={
      email:'',
      password:'',
      isLoading:false,
    }
  }

  LoginPress= async()=>{
    if(this.state.email&& this.state.password)
    {
      await firebase.auth().signInWithEmailAndPassword(this.state.email,this.state.password)
    .then(
      firebase.auth().onAuthStateChanged((user)=>
        var docRef=firebase.firestore().collection("Users").doc(user.uid);
        docRef.get().then((doc) => {
          if (doc.exists) {
              console.log("Document data:", doc.data());
              const {status} = doc.data();
              this.checkStatusLogin(status,{user});
              if(status==="Parent")
              { 
                 this.props.navigation.navigate("HomeParent",{user});
              }
      }).catch((error) => {
          console.log("Error getting document:", error);
      });
    }
  }))
    .catch((error)=>{
    }
    )
  }
  }

}

HomeParent.js :

class HomeParent extends React.Component {
  constructor(props){
    super(props)
    this.state={

    }
  }

  componentDidMount(){
    const {navigation}=this.props;
    const user=navigation.getParam('user');
  }
 
    render(){
        return(
              <View style={styles.logoContainer}>
                <Image source={Logo} style={styles.logo}/>
                <Text style={{alignItems:'center',justifyContent:'center',margin:40,fontSize:25}}>Home Parent</Text>
              </View>

)
        
    }
}

1 个答案:

答案 0 :(得分:1)

要传递参数,您需要在 HomeParent 中执行以下操作,

 constructor(props){
    super(props);

    const user = this.props.navigation.getParam('user');
    this.state={
    user,
    }

但理想情况下,这不是标准方式,您可以做的是将 userId 保存在 AsyncStorage 中,例如 AsyncStorage.setItem('userId'); 并获取 userId,您可以在 componentDidMount 中创建一个异步函数,例如

componentDidMount(){
this.handleData();
}

handleData=async()=>{
const userId = await AsyncStorage.getItem('userId');
}