反应本地-尝试从存储在本地存储中的json对象呈现单个值

时间:2019-09-02 04:32:18

标签: json react-native local-storage

我创建了一个登录组件,在其中将json对象存储在asynStorage中,它工作正常。 问题是,当我尝试从asynStorage中获取价值时,屏幕上什么也没有。

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

这行代码让我在屏幕上看到了整个json。

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

我只想显示电子邮件,所以我正在写此行 这条线给我什么。

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

我的组件代码是这样的

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>
    );
  }
}

我需要再问一件事, 我在登录组件中使用此代码,但是在按注销并从syncStorage中删除项目之后,它甚至会返回主屏幕,请告诉我为什么。

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

5 个答案:

答案 0 :(得分:2)

使用 AsyncStorage 时,我们必须了解它仅保留字符串。因此,它仅读取和写入字符串化的JSON。 这将起作用:

 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>
    );
  }

对于写操作:

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

结果:

enter image description here

更新:为代码添加迭代代码

考虑前面的代码,可以渲染所有数组元素:

 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>
   );
 }

答案 1 :(得分:0)

for 1st page
1 | 2 | 3
6 | 7 | 8
11| 12| 13
16| 17| 18


for 2nd page
3 | 4 | 5
8 | 9 | 10
18

这是一次麻烦,因此当您访问它时,请访问数组的第0个元素,然后在该元素上获取uemail属性。  {this.state.getValue [0] .uemail}

答案 2 :(得分:0)

您正在获取数组中的值,因此请使用数组的索引来显示值。 您必须在componentDidMount中使用async,因为从存储中获取数据是异步的

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


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

//关于此问题。

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

同样,从异步获取存储中的值是同样的问题。 将代码更新为:

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

答案 3 :(得分:0)

这是带有钩子的示例代码:

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;

答案 4 :(得分:0)

最后三天,经过多次尝试,我们得到了答案 谢谢@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>
    );
  }
}