【问题标题】:Store/ Save boolean values in AsyncStorage in react native将布尔值存储/保存在 AsyncStorage 中的反应本机中
【发布时间】:2017-10-24 17:27:11
【问题描述】:

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

这是我正在使用的代码 设置页面(设置值为真或假,但默认值为真)

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

但我一直在控制台中得到这个:

【问题讨论】:

    标签: serialization react-native save boolean async-await


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      相关资源
      最近更新 更多