Вы можете прослушивать события жизненного цикла событий.
Настройка довольно проста. Вот пример того, как настроить его на вашем экране.
import React, {Component} from 'react';
import { View, StyleSheet, Text } from 'react-native';
export default class Screen2 extends React.Component {
// willFocus - the screen will focus
// didFocus - the screen focused (if there was a transition, the transition completed)
// willBlur - the screen will be unfocused
// didBlur - the screen unfocused (if there was a transition, the transition completed)
componentDidMount () {
// add listener
this.willFocusSubscription = this.props.navigation.addListener('willFocus', this.willFocusAction);
this.didFocusSubscription = this.props.navigation.addListener('didFocus', this.didFocusAction);
this.willBlurSubscription = this.props.navigation.addListener('willBlur', this.willBlurAction);
this.didBlurSubscription = this.props.navigation.addListener('didBlur', this.didBlurAction);
}
componentWillUmount () {
// remove listener
this.willFocusSubscription.remove()
this.didFocusSubscription.remove();
this.willBlurSubscription.remove();
this.didBlurSubscription.remove();
}
willBlurAction = () => {
console.log('willBlur Screen', new Date().getTime())
}
didBlurAction = () => {
console.log('didBlur Screen', new Date().getTime());
}
didFocusAction = () => {
console.log('didFocus Screen', new Date().getTime());
}
willFocusAction = () => {
console.log('willFocus Screen', new Date().getTime());
}
render() {
return (
<View style={styles.container}>
<Text>Screen</Text>
</View>
)
}
}
Вам не нужно добавлять всех слушателей, только тех, которые вам нужны.
Скорее всего, вы захотите очистить свое значение от AsyncStorage
внутри события willFocus
. Таким образом, это происходит до того, как экран сфокусировался.