serialization - 在 React Native 中将 boolean 值存储/保存在 AsyncStorage 中

标签 serialization react-native save boolean async-await

我需要在 React Native 应用程序中将 boolean 值存储在 AsyncStorage 中。存储的值将在整个应用程序中使用。实际上,用户将在设置页面中将变量设置为 true 或 false,并根据该值,我在应用程序的其他页面中进行一些更改。

这是我正在使用的代码 设置页面(将值设置为 true 或 false 但默认值为 true)

    constructor(props) {
                super(props);
                this.state ={
                    status: true
                }
            };

      toggleStatus(){
                this.setState({
                    status:!this.state.status
                });

 // AsyncStorage.setItem('myCheckbox',JSON.stringify(this.state.status));

//I even hardcoded the value stored and set it to false but it didn't work 
       AsyncStorage.setItem('myCheckbox',  JSON.stringify(false));
                    }
        .. 
        <TouchableOpacity onPress={this.toggleStatus.bind(this)}>
            <Text> touch me </Text>
        </TouchableOpacity>

在其他页面之一中,我将使用存储在 AsyncStorage 中的值:

componentDidMount() {

        const value =   AsyncStorage.getItem('myCheckbox', (value) => {
            JSON.parse(value)
            console.log("my check box value ", value)
        });

但我不断在控制台中收到此消息:enter image description here

最佳答案

在 AsyncStorage ( here ) 的 React Native 文档中,它说所有方法都返回一个 Promise

您可以使用async/await,但我们将采用ES6方式。

AsyncStorage.getItem('myCheckbox').then((value) => {
 console.log(value);
});

关于serialization - 在 React Native 中将 boolean 值存储/保存在 AsyncStorage 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44157181/

相关文章:

java - 在 RuntimeExceptions 上使用列表的最佳方法是什么?

reactjs - 在 React Native 中在哪里添加 .d.ts 文件

node.js - 升级到 expo 31. react-native-dot-env 错误 : react native does not support node standard library

react-native - 在 Android Pay 流程 (getPaymentToken) 之后,支付 token 变得未定义

R 用 for 循环保存绘图(保存直方图有效)

java - 保存大量对象列表需要花费大量时间

android - 如何在服务器上购买空间并将其用于在 android 中存储和检索数据?

python - 在 Django : How to serialize dict object to json?

.net - 将 JSON 字符串反序列化为 VB.net 对象

c# - WCF 对象序列化问题