我需要在 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)
});
最佳答案
在 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/