英文:
React Navigation v6: How to detect when screen comes into or out of focus?
问题
在React Navigation v4中,您可以将您的组件包装在withNavigationFocus()
中,然后使用以下方式触发函数:
componentDidUpdate(prevProps) {
if (!prevProps.isFocused && this.props.isFocused) {
...
}
}
在React Navigation v6中是否有类似的方法?我看到的只是您可以使用useIsFocused()
来检测屏幕当前是否处于焦点状态,但无法检测何时刚刚进入/退出焦点。
英文:
In React Navigation v4, you could wrap your component in withNavigationFocus()
and then trigger a function using
componentDidUpdate(prevProps) {
if (!prevProps.isFocused && this.props.isFocused) {
...
}
}
Is there a way to do this in React Navigation v6? All I've seen is that you can use useIsFocused()
to detect if the screen is currently focused, but not to detect when it's just come into / out of focus.
答案1
得分: 3
使用useFocusEffect在屏幕聚焦时运行副作用。
useFocusEffect类似于React的useEffect钩子。唯一的区别是它仅在屏幕当前处于焦点状态时运行。
useFocusEffect(
React.useCallback(() => {
// 当屏幕处于焦点时执行某些操作
return () => {
// 当屏幕不再处于焦点时执行某些操作
};
}, [])
);
英文:
Use useFocusEffect to run side-effects when a screen is focused.
> The useFocusEffect is analogous to React's useEffect hook. The only difference is that it only runs if the screen is currently focused.
useFocusEffect(
React.useCallback(() => {
// Do something when the screen is focused
return () => {
// Do something when the screen is unfocused
};
}, [])
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论