简体   繁体   中英

Pass User data from screen to screen - React Native

I'm new to React Native and I'm trying to push and get (and print) the data user.uid from LoginAdult screen to HomeParent screen. In the HomeParent screen I want to user it (to pass it to other screens). It would be grateful if anyone helps me !

LoginAdult.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>

)
        
    }
}

To pass the params you need to do following things in HomeParent,

 constructor(props){
    super(props);

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

But ideally, this is not the standard way, what you can do is to save the userId in AsyncStorage, like AsyncStorage.setItem('userId'); and to get the userId, you can create a async function in componentDidMount like

componentDidMount(){
this.handleData();
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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