正如他们所指出的 在文档中他们已经摆脱了4个导航事件监听器,而决定使用 生命周期事件.
但我在使用React Navigation 5时遇到的问题就是 blur
事件不能如我所愿! 之前,我可以添加一个 onWillBlur
监听器,并在用户暂时离开(而不是关闭)应用程序时做一些事情(例如关闭一个套接字连接,然后在用户重新进入应用程序时重新打开它)。
我怎样才能复制 onWillBlur
或 onDidBlur
这样的用例的事件?我不需要知道在用户点击按钮后被带到B屏幕后,A屏幕是否模糊。
你可以使用钩子useFocusEffect。
EDIT:
添加了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 />;
}
EDIT 2.我没有在主页按钮上测试它,但我找到了一个帖子,对这个问题也有帮助。
我没有在主页按钮上进行测试,但我找到了一个帖子,也能帮到你。
我希望这次你对我的回答感到满意。
在这里,你有一个工作的例子。
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>
}