有没有办法用 AsyncStorage 存储字符串以外的值?例如,我想存储简单的 bool 值。
AsyncStorage.setItem('key', 'ok');
没问题,但是:
AsyncStorage.setItem('key', false);
不起作用..
最佳答案
基于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.
您可能想尝试看看第三方软件包。也许this one .
编辑 02/11/2016
感谢@Stinodes 的技巧。
虽然只能存储字符串,但也可以将对象和数组用JSON字符串化来存储,取出来再解析。
这仅适用于普通对象实例或数组,但是,从任何原型(prototype)继承的对象可能会导致意外问题。
一个例子:
// 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
}
})
关于ios - React Native AsyncStorage 存储字符串以外的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35596187/