Вы можете использовать хук useFocusEffect.
Документация здесь
РЕДАКТИРОВАТЬ:
Добавлен пример из React Navigation.
import { useFocusEffect } from '@react-navigation/native';
function Profile() {
useFocusEffect(
React.useCallback(() => {
// Do something when the screen is focused, onFocus
return () => {
// Do something when the screen is unfocused, onBlur
// Useful for cleanup functions
};
}, [])
);
return <ProfileContent />;
}
РЕДАКТИРОВАТЬ 2:
Я не проверял это на кнопке home, но нашел сообщение, которое тоже помогает с этим
Проверьте здесь
Надеюсь, на этот раз вы довольны моим ответом.
И вот у вас есть рабочий пример:
import React from 'react'
import { Text, AppState } from 'react-native'
const MyComponent = () => {
const [appState, setAppState] = React.useState(AppState.currentState)
React.useEffect(() => {
AppState.addEventListener('change', handleChanges)
setAppState(AppState.currentState)
return AppState.removeEventListener('change')
},[])
const handleChanges = (nextAppState) => {
if (appState.match(/inactive|background/) && nextAppState === 'active') {
console.log('App has come to the foreground!');
} else {
console.log('App has gone to the background!');
// start your background task here
}
setAppState(nextAppState)
}
return <Text>{appState}</Text>
}