简体   繁体   English

如何在 React Native 中本地存储不是字符串的数据

[英]How to store data locally in React Native that is not a string

I am looking for a way to store objects and arrays of data locally in React Native.我正在寻找一种在 React Native 中本地存储对象和数据数组的方法。 How can this be done?如何才能做到这一点? Looking at the api for AsyncStorage:查看 AsyncStorage 的 api:

static setItem (key: string, value: string, callback?: ?(error: ?Error) => void) 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.设置 key 的值并在完成时调用回调,如果有错误,则会出现错误。 Returns a Promise object.返回一个 Promise 对象。

How do I store objects and arrays locally in React Native?如何在 React Native 中本地存储对象和数组?

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.在下面的示例中,我使用 React Native 的内置 AsyncStorage API 作为“持久”存储设施。 Adapt it as you see fit.按照您认为合适的方式进行调整。

Example using React Native使用 React Native 的示例

Using the JSON API to store an object in persistent storage, ie React Native's AyncStorage, and then retrieving that value, and outputting it in a Text element.使用 JSON API 将对象存储在持久存储中,即 React Native 的 AyncStorage,然后检索该值,并将其输出到 Text 元素中。 Untested.未经测试。

Storage.js file - Note, this example object API provides a subset wrapper 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));
};

recently i write pleex, you can take look at it https://github.com/E-RROR/pleex .最近在写pleex,你可以看看https://github.com/E-RROR/pleex you can save data in pure json or creating schemas with typechecking feature and more.您可以将数据保存在纯 json 中或使用类型检查功能等创建模式。 thanks谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM