我存儲如果複選框被選中或不使用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在構造函數中沒有什麼區別。