我正在寻找一种在React Native中本地存储对象和数据数组的方法 . 如何才能做到这一点?查看AsyncStorage的api:
static setItem (key:string,value:string,callback?:?(error:?Error)=> void)设置键的值并在完成时调用回调,如果有则设置错误 . 返回Promise对象 .
如何在React Native中本地存储对象和数组?
JSON.stringify({})可用于将数据结构转换为字符串 .
然后,您可以使用JSON.parse()将字符串转换回原始数据结构 .
您可以为此创建一个很好的服务,以消除整个应用程序中的一些样板代码 . 我在下面的示例中使用了React Native的内置AsyncStorage API作为“持久性”存储工具 . 根据需要调整它 .
Example using 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> ); } }
Original example:
正如我最初在移动设备上回答的那样,我最初使用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)); };
1 回答
JSON.stringify({})可用于将数据结构转换为字符串 .
然后,您可以使用JSON.parse()将字符串转换回原始数据结构 .
您可以为此创建一个很好的服务,以消除整个应用程序中的一些样板代码 . 我在下面的示例中使用了React Native的内置AsyncStorage API作为“持久性”存储工具 . 根据需要调整它 .
Example using React Native
使用JSON API将对象存储在持久存储中,即React Native的AyncStorage,然后检索该值,并将其输出到Text元素中 . 未经测试 .
Storage.js文件 - 注意,此示例对象API提供了ReactNative的AsyncStorage API提供的子集包装器,您可以调整它以允许设置多个键,例如,而不是一次设置多个键 .
React Native组件
Original example:
正如我最初在移动设备上回答的那样,我最初使用HTML5 localStorage api作为一个例子,输入速度更快(而且很冷!),这里只是因为有人在这上面作出反应,而不是反应 - 本地的错误 .