目前有三种方法可以做到这一点,因为5.x
。你可以
- use
useFocusEffect
挂钩来触发操作(推荐),或者
- use
useIsFocused
钩子,或
- 听
focus
event
的例子useFocusEffect
import { useFocusEffect } from '@react-navigation/native';
function Sample(props) {
const [shouldHide, setShouldHide] = React.useState(false);
useFocusEffect(() => {
setShouldHide(false)
return () => {
setShouldHide(true)
}
});
return shouldHide ? null : <InnerComponent {...props} />;
}
的例子useIsFocused
hook
import * as React from 'react';
import { Text } from 'react-native';
import { useIsFocused } from '@react-navigation/native';
function Profile() {
// This hook returns `true` if the screen is focused, `false` otherwise
const isFocused = useIsFocused();
return {isFocused ? <Text>Inner component</Text> : null};
}
Note:
当屏幕进入和离开焦点时,使用此钩子组件可能会导致不必要的组件重新渲染。 ...
因此,我们建议仅在需要触发重新渲染时才使用此挂钩。
更多信息可以在文档中找到当焦点屏幕改变时调用函数 https://reactnavigation.org/docs/function-after-focusing-screen/
除此之外,堆栈导航器还带有一个名为detachInactiveScreens
默认情况下启用。文档链接 https://reactnavigation.org/docs/stack-navigator/#detachinactivescreens
detachInactiveScreens https://reactnavigation.org/docs/stack-navigator/#detachinactivescreens
布尔值用于指示是否应将非活动屏幕与视图层次结构分离以节省内存。请务必致电enableScreens
from react-native-screens
使其发挥作用。默认为true
.
(有关启用 React Native Screens 的说明可以在https://reactnavigation.org/docs/react-native-screens/#setup-when-you-are-using-expo https://reactnavigation.org/docs/react-native-screens/#setup-when-you-are-using-expo)
在堆栈导航器的内部options
对象,还有一个detachPreviousScreen
自定义某些屏幕的行为的 prop。通常也会启用此选项。
detachPreviousScreen https://reactnavigation.org/docs/stack-navigator/#detachpreviousscreen
布尔值用于指示是否从视图层次结构中分离上一个屏幕以节省内存。将其设置为false
如果您需要通过活动屏幕看到上一个屏幕。仅适用于detachInactiveScreens
未设置为 false。默认为false
对于最后一个屏幕,当mode='modal'
, 否则true
.