是否将json对象导出到react native中的本地存储?

nzk0hqpo  于 2022-12-14  发布在  React
关注(0)|答案(2)|浏览(121)

我正在从Firestore中获取一个JSON对象,我希望能够将其作为JSON文件导出到我的本地存储中。我该如何做呢?
以下是我的数据示例:

[
   {
      "date":1602214199274,
      "expenseType":{
         "id":"74aa77c2-d3c7-4456-9b5c-71cbefc5cc66",
         "name":"Raw materials",
         "userId":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx5"
      },
      "id":"ae1d7a8d-2492-46dd-8c69-97ef206e6fab",
      "key":"fd6ec236-6705-4a95-a698-13e2f25f08d2",
      "note":"Fugit quaerat et veritatis doloremque.",
      "supplier":{
         "id":"d55a8495-ec27-42b4-894b-a2a9fa0eb3a4",
         "name":"Yvonne Stokes",
         "phone":"1-!##-!##-####",
         "userId":"xxxxxxxxxxxxxxxxxxxxxxxxxxx"
      },
      "totalPrice":{
         "amount":"952.00",
         "currency":"USD"
      },
      "type":"EXPENSE"
   },
   {
      "date":1601695799282,
      "expenseType":{
         "id":"39c5eb85-0377-41fc-a549-ce590146ac26",
         "name":"Equipment",
         "userId":"xxxxxxxxxxxxxxxxxxxxxxx"
      },
      "id":"cee9d1c8-979c-496f-a56d-95e3f8474823",
      "key":"8c6cd4a2-f940-44be-bbf8-c0cab7631e37",
      "note":"Amet provident itaque neque mollitia.",
      "supplier":{
         "id":"36b51b24-7d07-410b-849c-4c92cb52c41e",
         "name":"Jack Macejkovic",
         "phone":"(!##) !##-####",
         "userId":"xxxxxxxxxxxxxxxxxe"
      },
      "totalPrice":{
         "amount":"378.00",
         "currency":"KHR"
      },
      "type":"EXPENSE"
   },]
0sgqnhkj

0sgqnhkj1#

您可以使用以下方法将其转换为字符串:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
安装异步存储:

npm i @react-native-community/async-storage

用法:

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

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

在此处查看文档:https://react-native-community.github.io/async-storage/docs/usage
然后,当您从本地存储中检索它时,可以进行解析:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

zkure5ic

zkure5ic2#

React本机异步存储(https://react-native-community.github.io/async-storage/)是一个字符串存储。因此,您必须使用JSON.stringify(json)将其转换为字符串,然后将其存储在异步存储中。它不等同于浏览器的存储。
如果你使用的是Android,AsyncStorage的大小被限制在几MB(默认为6MB)。如果需要,可以增加。
如果数据太大但有格式,则可以使用基于sql的db https://github.com/andpor/react-native-sqlite-storage(expo版本:https://docs.expo.io/versions/latest/sdk/sqlite/)的数据
否则,您将拥有https://realm.io/products/realm-databasehttps://github.com/realm/realm-js领域

相关问题