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

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

问题描述

我想用 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?

推荐答案

Async Storage 只能存储字符串数据,所以为了存储对象数据需要先序列化它.对于可以序列化为 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
  }
}

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

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