【问题标题】:How to store data in local storage with react native?如何使用本机反应将数据存储在本地存储中?
【发布时间】:2020-10-01 11:58:49
【问题描述】:

我想用 react native 和 redux 创建带有注释的待办事项列表。我有复杂的逻辑将笔记和待办事项存储在不同的地方,具有不同的状态。我应该如何将所有关系和所有数据存储在 Android/IOS 设备的本地存储中?

【问题讨论】:

  • 您应该避免将所有数据存储在本地存储中。它有一些内存限制!

标签: database react-native redux


【解决方案1】:

Async Storage 只能存储字符串数据,所以为了存储对象数据需要先序列化。对于可以序列化为 JSON 的数据,您可以在保存数据时使用 JSON.stringify(),在加载数据时使用 JSON.parse()。

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

【讨论】:

    【解决方案2】:

    为此,您可以使用类似https://github.com/react-native-community/async-storage

    但是,请注意 AsyncStorage 的限制,例如加密和大小。

    你可以这样使用它:

    import AsyncStorage from '@react-native-community/async-storage';
    
    export default {
      setItem: async (key, value) => {
        try {
          await AsyncStorage.setItem(key, JSON.stringify(value));
        } catch (error) {}
      },
      getItem: async (key) => {
        try {
          const item = await AsyncStorage.getItem(key);
    
          return JSON.parse(item);
        } catch (error) {}
      },
      removeItem: async (key) => {
        try {
          await AsyncStorage.removeItem(key);
        } catch (error) {}
      },
      updateItem: async (key, value) => {
        try {
          const item = await AsyncStorage.getItem(key);
          const result = {...JSON.parse(item), ...value};
    
          await AsyncStorage.setItem(key, JSON.stringify(result));
        } catch (error) {}
      },
    };
    

    【讨论】:

      猜你喜欢
      • 2019-03-28
      • 2013-08-17
      • 2019-02-20
      • 2020-12-19
      • 1970-01-01
      • 2018-05-06
      • 2018-01-11
      • 1970-01-01
      • 2017-09-01
      相关资源
      最近更新 更多