如何使用React Native将数据存储在本地存储中? [英] How to store data in local storage with react native?

查看:101
本文介绍了如何使用React Native将数据存储在本地存储中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用响应本机和redux的注释创建待办事项列表.我有在不同位置以不同状态存储便笺和待办事项的复杂逻辑.如何将所有关系和所有数据存储在Android/IOS设备的本地存储中?

I want to create todo list with notes with react native and redux. I have complicated logic of storing notes and todos in different places, with different statuses. How should I store all relations and all data in local storage in Android/IOS devices?

推荐答案

异步存储只能存储字符串数据,因此要存储对象数据,您需要先对其进行序列化.对于可以序列化为JSON的数据,可以在保存数据时使用JSON.stringify(),在加载数据时使用JSON.parse().

Async Storage can only store string data, so in order to store object data you need to serialize it first. For data that can be serialized to JSON you can use JSON.stringify() when saving the data and JSON.parse() when loading the data.

import AsyncStorage from '@react-native-community/async-storage';

存储字符串值

const storeData = async (value) => {
  try {
    await AsyncStorage.setItem('@storage_Key', value)
  } catch (e) {
    // saving error
  }
}

排序对象值

const storeData = async (value) => {
 try {
    const jsonValue = JSON.stringify(value)
    await AsyncStorage.setItem('@storage_Key', jsonValue)
  } catch (e) {
    // saving error
  }
}

读取字符串值

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

读取对象值

const getData = async () => {
  try {
    const jsonValue = await AsyncStorage.getItem('@storage_Key')
    return jsonValue != null ? JSON.parse(jsonValue) : null;
  } catch(e) {
    // error reading value
  }
}

这篇关于如何使用React Native将数据存储在本地存储中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆