javascript 如何在 React Native 中本地存储不是字符串的数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33790143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store data locally in React Native that is not a string
提问by Nader Dabit
I am looking for a way to store objects and arrays of data locally in React Native. How can this be done? Looking at the api for AsyncStorage:
我正在寻找一种在 React Native 中本地存储对象和数据数组的方法。如何才能做到这一点?查看 AsyncStorage 的 api:
static setItem(key: string, value: string, callback?: ?(error: ?Error) => void)
Sets value for key and calls callback on completion, along with an Error if there is any. Returns a Promise object.
static setItem(key: string, value: string, callback?: ?(error: ?Error) => void)
设置键的值并在完成时调用回调,如果有错误,也会出现错误。返回一个 Promise 对象。
How do I store objects and arrays locally in React Native?
如何在 React Native 中本地存储对象和数组?
回答by Lee Brindley
JSON.stringify({}) can be used to convert your data structure to a string.
JSON.stringify({}) 可用于将您的数据结构转换为字符串。
You'd then use JSON.parse() to convert the string back to the original data structure.
然后,您将使用 JSON.parse() 将字符串转换回原始数据结构。
You could create a nice service for this to eliminate some boilerplate code throughout your app. I've used React Native's built-in AsyncStorage API as the "persistent" storage facility in the example below. Adapt it as you see fit.
您可以为此创建一个很好的服务,以消除整个应用程序中的一些样板代码。在下面的示例中,我使用 React Native 的内置 AsyncStorage API 作为“持久”存储设施。按照您认为合适的方式进行调整。
Example using React Native
使用 React Native 的示例
Using the JSON API to store an object in persistent storage, i.e. React Native's AyncStorage, and then retrieving that value, and outputting it in a Text element. Untested.
使用 JSON API 将对象存储在持久存储中,即 React Native 的 AyncStorage,然后检索该值,并将其输出到 Text 元素中。未经测试。
Storage.js file - Note, this example object API provides a subsetwrapper around what ReactNative's AsyncStorage API provides, you could adapt it to allow setting multiple keys for example, rather than one at a time.
Storage.js 文件 - 请注意,此示例对象 API 提供了一个围绕 ReactNative 的 AsyncStorage API 提供的内容的子集包装器,您可以对其进行调整以允许设置多个键,例如,而不是一次设置一个。
//./storage.js
const Storage = {
getItem: async function (key) {
let item = await AsyncStorage.getItem(key);
//You'd want to error check for failed JSON parsing...
return JSON.parse(item);
},
setItem: async function (key, value) {
return await AsyncStorage.setItem(key, JSON.stringify(value));
},
removeItem: async function (key) {
return await AsyncStorage.removeItem(key);
}
};
React Native component
反应原生组件
//Usage...
import React, {Component} from "react";
import { View, Text } from "react-native";
import Storage from "./storage";
class Foo extends Component {
constructor (props) {
super(props);
this.state = {
greeting: ""
};
}
async componentDidMount () {
await Storage.setItem("someObj", {value: "bar", id: 1});
let obj = await Storage.getItem("someObj");
this.setState({
greeting: obj.value // Will be "bar"
});
}
render () {
return (
<View>
<Text>{this.state.greeting}</Text>
</View>
);
}
}
Original example:
原始示例:
As I originally answered this on mobile, I did originally use the HTML5 localStorage api as an example, it was quicker to type (and it was cold!), here it is just in-case someone lands on this for react, not react-native mistakenly.
当我最初在移动设备上回答这个问题时,我最初确实使用 HTML5 localStorage api 作为示例,它的输入速度更快(而且很冷!),这里只是以防万一有人登陆它进行反应,而不是反应-本地错误。
var StorageService = function () {};
StorageService.prototype.get = function (key) {
return JSON.parse(window.localStorage.getItem(key));
};
StorageService.prototype.set = function (key, value) {
return window.localStorage.setItem(key, JSON.stringify(value));
};
回答by sina farhadi
recently i write pleex, you can take look at it https://github.com/E-RROR/pleex. you can save data in pure json or creating schemas with typechecking feature and more. thanks
最近在写pleex,你可以看看https://github.com/E-RROR/pleex。您可以将数据保存在纯 json 中,或者使用类型检查功能等创建模式。谢谢