我存储如果复选框被选中或不使用AsyncStorage。当我重新加载应用程序时,我从日志中看到异步变量内存储了正确的信息。但是,它在componentWillMount之后加载。因此,该复选框不会显示为已选中状态,因为它应该是。React Native - 异步存储信息被提取后componentWillMount()
我认为一个很好的解决方法是更改异步函数内的复选框属性。你认为这是一个很好的解决方案吗?您是否有其他建议来显示正确的复选框值?
我的代码:
constructor(props) {
super(props)
this.state = {isChecked: false}
this.switchStatus = this.switchStatus.bind(this)
}
async getCache(key) {
try {
const status = await AsyncStorage.getItem(key);
if (status == null)
status = false
console.log("my async status is " + status)
return status
} catch(error) {
console.log("error", e)
}
}
componentWillMount(){
// key string depends on the object selected to be checked
const key = "status_" + this.props.data.id.toString()
this.getCache = this.getCache.bind(this)
this.setState({isChecked: (this.getCache(key) == 'true')})
console.log("my state is" + this.state.isChecked)
}
switchStatus() {
const newStatus = this.state.isChecked == false ? true : false
AsyncStorage.setItem("status_" + this.props.data.id.toString(), newStatus.toString());
console.log("hi my status is " + newStatus)
this.setState({isChecked: newStatus})
}
render({ data, onPress} = this.props) {
const {id, title, checked} = data
return (
<ListItem button onPress={onPress}>
<CheckBox
style={{padding: 1}}
onPress={(this.switchStatus}
checked={this.state.isChecked}
/>
<Body>
<Text>{title}</Text>
</Body>
<Right>
<Icon name="arrow-forward" />
</Right>
</ListItem>
)
}
还有,如果我把一切都放在componentWillMount在构造函数中没有什么区别。