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

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

本文关键字:存储 数据 Native React 字符串      更新时间:2023-09-26

我正在寻找一种在React Native中本地存储对象和数据数组的方法。如何做到这一点?查看AsyncStorage的api:

staticsetItem(键:字符串,值:字符串,回调?:?(错误:?错误)=>无效)
设置键的值,并在完成时调用回调,如果有错误,还会调用Error。返回Promise对象

如何在React Native中本地存储对象和数组?

JSON.stringfy({})可以用于将数据结构转换为字符串。

然后使用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));
};

最近我写了pleex,你可以看看它https://github.com/E-RROR/pleex.您可以将数据保存在纯json中,或者创建具有类型检查功能的模式等等。感谢