react native - trying to render single value from json object stored in localstorage

被刻印的时光 ゝ 提交于 2019-12-24 11:21:09

问题


I created a login component where i stored a json object in asynStorage it is working fine. Problem is that when i trying to get the value from asynStorage, i am not getting anything on screen.

<Text> { this.state.getValue } </Text> 

This line giving me the whole json like this on screen.

[{
  "id":"9",
  "uname":"mine",
  "uemail":"mine@gmail.com",
  "upass":"nomination"
}]

I want display the email only so i am writing this line This line giving me nothing.

<Text> { this.state.getValue.uemail } </Text>

My component code is like this

export default class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
           getValue:''
        };
    }

    componentDidMount() {
      let userData = AsyncStorage.getItem('user').then(value => {
        this.setState({ getValue : value })
      });
    }

  render() {
    return (
        <View style={{marginTop:30, marginLeft:20, marginRight:20, marginBottom:30}}>
            <Text> { this.state.getValue } </Text> 
            <Text> { this.state.getValue.uemail } </Text>          
        </View>
    );
  }
}

One more thing i need to ask that, I am using this code in Login component but after pressing logout and removing item from syncStorage it is even going to home screen after that, please tell me why ?.

componentDidMount() {
  let userData = AsyncStorage.getItem('user');
  if(userData){
    this.props.navigation.navigate('Home');
  }
}

回答1:


When working with AsyncStorage we must understand that it only keep strings. So it only read and write stringified JSON. This will work:

 constructor(props){
    super(props);
    this.state = {
      getValue: null, //<-- initialize null
    }
 }

 componentDidMount() {
    AsyncStorage.getItem('user').then(value => {
      this.setState({ getValue: JSON.parse(value) }); //read like a stringified JSON
    });
 }

 render() {
    return (
      <View>
        <Text>Tela2 : {this.state.getValue ? this.state.getValue[0].uemail : ''}</Text>
      </View>
    );
  }

For write does:

  const a = [
    {
      "id": "9",
      "uname": "mine",
      "uemail": "mine@gmail.com",
      "upass": "nomination",
    },
  ];
  AsyncStorage.setItem('user', JSON.stringify(a));//<-- stringify your array here

Result:

UPDATE: ADD CODE FOR ITERATION IN ARRAY

Considering the previous code, to render all array elements do it:

 constructor(props){
    super(props);
    this.state = {
      getValue: [], //<-- in this case, start as empty array
    }
 }

 render() {
   return (
     <View>
       {this.state.getValue.map(value => {
         return(<Text>{value.uemail}</Text>)
       })}
     </View>
   );
 }



回答2:


[{
  "id":"9",
  "uname":"mine",
  "uemail":"mine@gmail.com",
  "upass":"nomination"
}]

This is an arry so when you are accessing it, access the 0th element of the array and then on that get the uemail property. { this.state.getValue[0].uemail }




回答3:


You are getting the value in array so use indices of array to show the value. You have to use async in componentDidMount because getting data from storage is in async

async componentDidMount() {
      let userData =await AsyncStorage.getItem('user').then(value => {
        this.setState({ getValue : value })
      });
    }


<Text> { this.state.getValue[0].uemail } </Text>

//About this issue.

  componentDidMount() {
      let userData = AsyncStorage.getItem('user');
      if(userData){
        this.props.navigation.navigate('Home');
      }
    }

Again it is the same problem of getting the value from storage works in async. Update the code as :

async componentDidMount() {
          let userData =await AsyncStorage.getItem('user');
          if(userData){
            this.props.navigation.navigate('Home');
          }
        }



回答4:


Here is a sample code with hooks:

import React, {useState, useEffect} from 'react';
import {Text} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';

const Home = () => {
  const [userDetails, setUserDetails] = useState({});

  useEffect(() => {
    AsyncStorage.getItem('user').then(savedData => {
      if (savedData) {
        try {
          const savedUserDetails = JSON.parse(savedData);
          if (savedUserDetails[0]) {
            setUserDetails(savedUserDetails[0]);
          }
        } catch (error) {}
      }
    });
  });

  const {id, uname, uemail, upass} = userDetails;

  return (
    <>
      <Text>{id}</Text>
      <Text>{uname}</Text>
      <Text>{uemail}</Text>
      <Text>{upass}</Text>
    </>
  );
};

export default Home;



回答5:


Finally after 3 days and many tries we got the answer Thank you @Aristofanio Garcia

export default class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
           getValue:[]
        };
    }


    async componentDidMount() {
      let getValue = await AsyncStorage.getItem('user');
      this.setState({ 
        getValue: JSON.parse(getValue), 
      });        
    }

  render() {

    return (
        <View style={{marginTop:30, marginLeft:20, marginRight:20, marginBottom:30}}>
            <Text style={{color:'black'}}> { this.state.getValue.toString() } </Text> 

            {this.state.getValue.map(member => {
               return(<Text style={{color:'black'}}>{member.uemail}</Text>)
            })}      
        </View>
    );
  }
}


来源:https://stackoverflow.com/questions/57751454/react-native-trying-to-render-single-value-from-json-object-stored-in-localsto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!