This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.

使用 React Activity 管理不活跃的路由

了解如何在保留状态的同时释放不活跃路由的资源。


React 的 <Activity> 可以在保持其状态的同时隐藏不活跃的路由内容。隐藏的内容会清理副作用并释放资源,直到它再次可见。

在导航器上启用活动处理,并为各个路由覆盖它:

🌐 Enable activity handling on a navigator and override it for individual routes:

src/app/_layout.tsx
import { Stack } from 'expo-router'; export default function RootLayout() { return ( <Stack activityEnabled> {/* Keep this screen active while another screen covers it. */} <Stack.Screen name="music" activityEnabled={false} /> {/* Hide this screen as soon as another screen covers it. */} <Stack.Screen name="editor" activityEnabled={1} /> {/* Hide this screen when three screens are above it. */} <Stack.Screen name="feed" activityEnabled={3} /> </Stack> ); }

配置屏幕隐藏时间

🌐 Configure when screens hide

对于 Stack,当上方有两个屏幕时,activityEnabled 会隐藏一个屏幕。正数会改变这个阈值。将其设置为 1 会在屏幕失去焦点时立即隐藏它。

🌐 For a Stack, activityEnabled hides a screen when two screens are above it. A positive number changes this threshold. Setting it to 1 hides the screen as soon as it loses focus.

当屏幕失去焦点时,JavaScript 标签页、本地标签页、无头标签页和抽屉会隐藏它。

🌐 JavaScript tabs, native tabs, headless tabs, and drawers hide a screen when it loses focus.

手动封装路由内容

🌐 Wrap route content manually

当你只需要封装屏幕的一部分时,使用 <NavigationAwareActivity>:

🌐 Use <NavigationAwareActivity> when you need to wrap only part of a screen:

src/app/details.tsx
import { NavigationAwareActivity } from 'expo-router'; import { useEffect } from 'react'; import { Text } from 'react-native'; function Details() { useEffect(() => { console.log('Details became visible'); return () => console.log('Details became hidden'); }, []); return <Text>Details</Text>; } export default function DetailsScreen() { return ( <NavigationAwareActivity hideWhenNestedAtLevel={1}> <Details /> </NavigationAwareActivity> ); }

当屏幕隐藏时,会运行 effect 清理。React 会保留组件的状态,所以组件不会卸载。

🌐 The effect cleanup runs when the screen hides. React preserves the component's state, so the component does not unmount.

<NavigationAwareActivity> 必须在路由屏幕内渲染。有关所有活动选项,请参阅 Expo Router API参考。