通过异步saveToStorage(userData)获取不同页面中的保存数据

时间:2019-07-31 07:42:24

标签: react-native

我正在创建一个本地本机应用程序,并正在执行登录和个人资料页面。我已经使用“异步saveToStorage(userData)”来保存用户数据。现在,我想在个人资料页面中获得相同的数据。

我要使用此

getData = async () => {
  try {
    const value = await AsyncStorage.getItem('@storage_Key')
    if(value !== null) {
      // value previously stored
    }
  } catch(e) {
    // error reading value
  }
}

但是如何在我的个人资料页面中使用它来显示此内容。

我将其保存在登录页面

  async saveToStorage(userData){
    if (userData) {
      await AsyncStorage.setItem('user', JSON.stringify({
          isLoggedIn: true,
          authToken: userData.auth_token,
          id: userData.user_id,
          name: userData.user_login
        })
      );
      return true;
    }

    return false;
  }

在“个人资料”页面中,我只需要显示名称。那怎么用呢?

import AsyncStorage from '@react-native-community/async-storage';
export default class Profile extends Component {
  constructor(props){
    super(props)
    this.state={
      userEmail:'',
      userPassword:'',
    }
  }
  var uservalue = await AsyncStorage.getItem('user');
  home() {
      Actions.home()
  }
  render() {
    return (
      <View style={styles.container}>
          <View style={styles.header}></View>
          <Image style={styles.avatar} source={{uri: 'https://bootdey.com/img/Content/avatar/avatar6.png'}}/>
          <View style={styles.body}>
            <View style={styles.bodyContent}>
              <Text style={styles.name}>Robert Vadra</Text>
              <Text style={styles.info}>Total Token: 30 {uservalue.name}</Text>
              <Text style={styles.description}>Lorem ipsum dolor sit amet, saepe sapientem eu nam. Qui ne assum electram expetendis, omittam deseruisse consequuntur ius an,</Text>

             <TouchableOpacity style={styles.buttonContainer} onPress={this.home} >
               <Text style={styles.buttonText}>Play Now</Text>
             </TouchableOpacity>
            </View>
        </View>
      </View>
    );
  }
}

在“ Robert Vadra”的地方,我想在其中显示存储的值。请帮忙。预先感谢。

我的登录页面

export default class LoginForm extends Component<{}> {

  constructor(props){
    super(props)
    this.state={
      isLoggedIn:false,
      userEmail:'',
      userPassword:'',
    }
  }

  login = () =>{
    this.state.validating = true;
    const {userEmail,userPassword} = this.state;
    let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ ;
    if(userEmail==""){
      this.setState({email:'Please enter Email address'})
    }

    else if(reg.test(userEmail) === false)
    {
    this.setState({email:'Email is Not Correct'})
    return false;
      }

    else if(userPassword==""){
    this.setState({email:'Please enter password'})
    }
    else{
      fetch('http://mojse.com/wetest/userlogin.php',{
        method:'post',
        header:{
          'Accept': 'application/json',
          'Content-type': 'application/json'
        },
        body:JSON.stringify({
          email: userEmail,
          password: userPassword
        })

      })
      .then((response) => response.json())
       .then((responseJson)=>{
          let data = responseJson.data;
          if (this.saveToStorage(data)){
            /* Redirect to home page */
            Actions.profile()
          } else {
            alert("Wrong Login Details");
          }

       })
       .catch((error)=>{
       console.error(error);
       });
    }


    Keyboard.dismiss();
  }
    render(){
        return(
            <View style={styles.container}>
          <TextInput style={styles.inputBox} 
              underlineColorAndroid='rgba(0,0,0,0)' 
              placeholder="Email"
              placeholderTextColor = "#ffffff"
              selectionColor="#fff"
              keyboardType="email-address"
              onChangeText={userEmail => this.setState({userEmail})}
              />
          <TextInput style={styles.inputBox} 
              underlineColorAndroid='rgba(0,0,0,0)' 
              placeholder="Password"
              secureTextEntry={true}
              placeholderTextColor = "#ffffff"
              ref={(input) => this.password = input}
              onChangeText={userPassword => this.setState({userPassword})}
              />  
           <TouchableOpacity style={styles.button} onPress={this.login} >
             <Text style={styles.buttonText}>Login</Text>
           </TouchableOpacity>     
        </View>
            )
    }

  async saveToStorage(userData){
    if (userData) {
      await AsyncStorage.setItem('user', JSON.stringify({
          isLoggedIn: true,
          authToken: this.state.authToken,
          id: this.state.userid,
          name: "KKKKKK"
        })
      );
      return true;
    }

    return false;
  }
}

1 个答案:

答案 0 :(得分:1)

您可以在componentDidMount中获取用户数据并将其保存为如下状态:

    constructor(props){
       super(props)
       this.state={
          userEmail:'',
          userPassword:'',
          userName:'',
       }
    }

    componentDidMount() {
        AsyncStorage.getItem('user').then((uservalue)=>{
            uservalue = JSON.Parse(uservalue)
            this.setState({userName: uservalue.name})
        })
    }

现在,您可以像这样使用userName:

<Text style={styles.name}>{this.state.userName}</Text>

编辑

首先,请检查服务器响应是否正确(保存前,也许console.log(data))。其次,您正在调用异步函数,因此必须等到保存函数完成其工作。同样在保存功能中,请仔细检查您的数据。我的建议:

fetch('http://mojse.com/wetest/userlogin.php',{
    method:'post',
    header:{
      'Accept': 'application/json',
      'Content-type': 'application/json'
    },
    body:JSON.stringify({
      email: userEmail,
      password: userPassword
    })

  })
  .then((response) => response.json())
   .then(async (responseJson) => {    // this is an async function
      let data = responseJson.data;
      console.log(data) // check and validate data correction
      let res = await this.saveToStorage(data)
      if (res){
        /* Redirect to home page */
        Actions.profile()
      } else {
        alert("Wrong Login Details");
      }

   })
   .catch((error)=>{
   console.error(error);
   });


   saveToStorage = async (userData) => {
      if (userData) {
          let model = {     // full model with received data. this.state. authToken is not valid because we do not have a state called authToken.
              isLoggedIn: true,
              authToken: userData.authToken,
              id: userData.userid,
              name: userData.name
          }
          await AsyncStorage.setItem('user', JSON.stringify(model))
          return true;
      }
      return false;
  }

这就是我认为可能是错误的,我没有对其进行测试。请仔细检查您的代码。

希望这对您有所帮助。