ios React Native AsyncStorage 存储字符串以外的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35596187/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:35:14  来源:igfitidea点击:

React Native AsyncStorage storing values other than strings

ioslocal-storagestoragereact-native

提问by Hasen

Is there any way to store values other than strings with AsyncStorage? I want to store simple boolean values for example.

有没有办法用 AsyncStorage 存储字符串以外的值?例如,我想存储简单的布尔值。

AsyncStorage.setItem('key', 'ok');

Is no problem, but:

没问题,但是:

AsyncStorage.setItem('key', false);

Does not work..

不起作用..

回答by G. Hamaide

Based on the AsyncStorage React-native docs, I'm afraid you can only store strings..

基于AsyncStorage React-native docs,恐怕您只能存储字符串..

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.

设置 key 的值并在完成时调用回调,如果有错误,则会出现错误。返回一个 Promise 对象。

You might want to try and have a look at third party packages. Maybe this one.

您可能想尝试查看第三方软件包。也许这个

Edit 02/11/2016

编辑 02/11/2016

Thanks @Stinodes for the trick.

感谢@Stinodes 的技巧。

Although you can only store strings, you can also stringify objects and arrays with JSON to store them, then parse them again after retrieving them.

虽然你只能存储字符串,但你也可以用 JSON 字符串化对象和数组来存储它们,然后在检索它们后再次解析它们。

This will only work properly with plain Object-instances or arrays, though, Objects inheriting from any prototypes might cause unexpected issues.

这仅适用于普通对象实例或数组,但是,从任何原型继承的对象可能会导致意外问题。

An example :

一个例子 :

// Saves to storage as a JSON-string
AsyncStorage.setItem('key', JSON.stringify(false))

// Retrieves from storage as boolean
AsyncStorage.getItem('key', (err, value) => {
    if (err) {
        console.log(err)
    } else {
        JSON.parse(value) // boolean false
    }
})

回答by stinodes

You can only store strings, but you can totally stringify objects and arrays with JSON, and parse them again when pulling them out of local storage.
This will only work properly with plain Object-instances or arrays, though.

您只能存储字符串,但您可以使用 JSON 完全字符串化对象和数组,并在将它们从本地存储中拉出时再次解析它们。
不过,这只适用于普通Object实例或数组。

Objects inheriting from any prototype might cause some unexpected behaviour, as prototypes won't be parsed to JSON.

从任何原型继承的对象可能会导致一些意外行为,因为原型不会被解析为 JSON。

Booleans (or any primitive for that matter) can be stored using JSON.stringify, though.
JSON recognises these types, and can parse them both ways.

JSON.stringify不过,可以使用 存储布尔值(或任何与此相关的原语)。
JSON 可以识别这些类型,并且可以通过两种方式解析它们。

JSON.stringify(false) // "false"
JSON.parse("false")   // false

So:

所以:

// Saves to storage as a JSON-string
AsyncStorage.setItem('someBoolean', JSON.stringify(false))

// Retrieves from storage as boolean
AsyncStorage.getItem('someBoolean', function (err, value) {
    JSON.parse(value) // boolean false
}

// Or if you prefer using Promises
AsyncStorage.getItem('someBoolean')
    .then( function (value) {
        JSON.parse(value) // boolean false
    })


// Or if you prefer using the await syntax
JSON.parse(await AsyncStorage.getItem('someBoolean')) // boolean false

After getting and parsing the value (which does not have to be a boolean, it can be an object. Whichever satisfies your needs), you can set in to the state or do whatever with it.

获取并解析值(不一定是布尔值,它可以是对象。只要满足您的需要),您就可以设置状态或对其进行任何操作。

回答by BK19

I have set value in "name" key in AsyncStorage

我在 AsyncStorage 的“name”键中设置了值

AsyncStorage.setItem("name", "Hello");

To get value from key "name"

从键“名称”中获取值

AsyncStorage.getItem("name").then((value) => {
   console.log("Get Value >> ", value);
}).done();

Output will be as follows:

输出如下:

'Get Values >> ', 'Hello'

回答by Lee Brindley

I always use/create a wrapper modulee around AsyncStorage, utilising JSON.parse & JSON.stringify on the data coming in and out.

我总是在 AsyncStorage 周围使用/创建一个包装模块,在传入和传出的数据上使用 JSON.parse 和 JSON.stringify。

This way you remove the need to have you JSON.parse & JSON.stringify calls inside your business logic. This keeps the code a bit nicer on the eye.

通过这种方式,您无需在业务逻辑中使用 JSON.parse 和 JSON.stringify 调用。这使代码看起来更好看。

Something like

就像是

import AsyncStorage from "@react-native-community/async-storage";

export const Storage {

    getItem: async (key) => {
        try {
             let result = await AsyncStorage.getItem(key);
             return JSON.parse(result);
        } 
        catch (e) {
             throw e;
        } 
    },

    setItem: async (key, value) => {

        try {
            const item = JSON.stringify(value);

            return await AsyncStorage.setItem(key, item);
        } catch (e) {
            throw e;
        }
    }
}

// usage

async function usage () {

    const isLeeCool = true;
    const someObject = { name: "Dave" };
    const someArray = ["Lee", "Is", "Cool."];

    try {
        // Note Async storage has a method where you can set multiple values,
        // that'd be a better bet here (adding it to the wrapper).
        await Storage.setItem("leeIsCool", leeIsCool);
        await Storage.setItem("someObject", someObject);
        await Storage.setItem("someArray", someArray);
    }  catch (e) {}

    // Some point later that day...

    try {

        console.log(await Storage.getItem("leeIsCool"));
        console.log(await Storage.getItem("someObject"));
        console.log(await Storage.getItem("someArray"));
    }  catch (e) {}
}

回答by rufeng

Certainly, you can use react-native-easy-appthat is easier to use than async storage. this library is great that uses async storage to save data asynchronously and uses memory to load and save data instantly synchronously, so we save data async to memory and use in app sync, so this is great.

当然,您可以使用比异步存储更易于使用的react-native-easy-app。这个库很棒,它使用异步存储异步保存数据并使用内存同步加载和保存数据,所以我们将数据异步保存到内存并在应用程序同步中使用,所以这很棒。

import { XStorage } from 'react-native-easy-app';

const RNStorage = { customerId: undefined ,isShow : undefined, userInfo: undefined }

XStorage.init(RNStorage,()=> {

   RNStorage.customerId='123456XXX'; // equivalent to AsyncStorage.setItem('customerId')

   RNStorage.isShow = false; // equivalent to AsyncStorage.setItem('customerId')

   RNStorage.userInfo = { name:'rufeng', age:30};

   console.log(RNStorage.customerId); // equivalent to AsyncStorage.getItem('customerId')

})

回答by Keshav Gera

 await AsyncStorage.setItem('saveUserCredential', JSON.stringify(true/false), () => {
        console.log("saveUserCredential save details " +flag);
 });



  AsyncStorage.getItem('saveUserCredential').then(async (value) => {
               let userLogin = await JSON.parse(value);

               if(userLogin ){
                   this.props.navigation.navigate("HomeScreen");
               }else {
                  this.props.navigation.navigate("LoginScreen");
               }
           });