JSON.stringify({}) 可用于将您的数据结构转换为字符串。
然后您将使用 JSON.parse() 将字符串转换回原始数据结构。
您可以为此创建一个很好的服务来消除整个应用程序中的一些样板代码。在下面的示例中,我使用了 React Native 的内置 AsyncStorage API 作为“持久”存储工具。按照您认为合适的方式进行调整。
使用 React Native 的示例
使用 JSON API 将对象存储在持久存储中,即 React Native 的 AyncStorage,然后检索该值,并将其输出到 Text 元素中。未经测试。
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 组件
//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>
);
}
}
原例:
正如我最初在移动设备上回答的那样,我最初确实使用 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));
};