反应本机AsyncStorage存储字符串以外的值 [英] React Native AsyncStorage storing values other than strings

查看:275
本文介绍了反应本机AsyncStorage存储字符串以外的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了使用AsyncStorage存储的字符串外,还有什么方法可以存储其他值?例如,我想存储简单的布尔值.

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

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

没问题,但是:

AsyncStorage.setItem('key', false);

不起作用..

推荐答案

基于

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

static setItem(key: string, value: string, callback?: ?(error: ?Error)
> => void) 

设置键的值并在完成时调用回调,以及 如果有错误.返回一个Promise对象.

Sets value for key and calls callback on completion, along with an Error if there is any. Returns a Promise object.

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

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

编辑2016年11月11日

感谢@Stinodes的把戏.

Thanks @Stinodes for the trick.

尽管您只能存储字符串,但是也可以使用JSON对对象和数组进行字符串化处理以存储它们,然后在检索它们之后再次对其进行解析.

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.

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

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

一个例子:

// 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
    }
})

这篇关于反应本机AsyncStorage存储字符串以外的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆