Ich speichere, wenn ein Kontrollkästchen aktiviert ist oder nicht AsyncStorage verwenden. Wenn ich die App neu lade, sehe ich von Logs, dass innerhalb der asynchronen Variablen die richtige Information gespeichert ist. Aber es wird nach componentWillMount geladen. Aus diesem Grund scheint das Kontrollkästchen nicht aktiviert zu sein, wie es sein sollte.React Native - Async-Speicherinformationen werden nach ComponentWillMount() extrahiert
Ich denke, eine gute Problemumgehung wird sein, die Checkbox-Eigenschaften in der asynchronen Funktion zu ändern. Denken Sie, dass das eine gute Lösung wäre? Haben Sie weitere Vorschläge zum Anzeigen des korrekten Kontrollkästchenwerts?
Mein Code:
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>
)
}
Es gibt keinen Unterschied, ob ich alles in componentWillMount im Konstruktor setzen.