Expo Router中使用Link导航或栈推送页面时首屏重复渲染的问题咨询
Hey there! Let's dig into your issue: the behavior you're seeing (your Home screen getting unmounted/re-mounted when navigating to/from Details) is not the default expected behavior for Expo Router's Stack navigation. Normally, when you push a new screen onto the stack, the previous screen should stay mounted in the background, so you shouldn't see the cleanup function run, nor should the Home screen re-render from scratch when you navigate back.
Let's break down the possible causes and fixes step by step:
1. Fix Your Stack Layout Configuration
Looking at your _layout.tsx, you only explicitly registered the index screen in the Stack, but not details. While Expo Router auto-matches routes, explicitly adding all stack screens helps avoid unexpected navigation behavior. Update your layout like this:
// app/_layout.tsx import { Stack } from "expo-router"; export default function Layout() { console.log("Layout rendered"); return ( <Stack> <Stack.Screen name="index" options={{ headerShown: false }} /> {/* 显式注册details路由 */} <Stack.Screen name="details" options={{ headerShown: false }} /> </Stack> ); }
2. Check for Unintended Unmounting Settings
The key clue here is that you're seeing your Home screen's cleanup function run when you navigate away. This means the Home component is being completely unmounted instead of being kept in the navigation stack. The most common reason for this is:
- Accidentally setting
unmountOnBlur: trueon yourindexroute'sStack.Screen. Double-check that this prop is either omitted (default isfalse) or explicitly set tofalse:<Stack.Screen name="index" options={{ headerShown: false }} // 确保这个属性不要设为true! // unmountOnBlur={false} />
3. Verify Your React.memo Usage
Your Home component is wrapped in React.memo correctly, but just to confirm:
- The
Itemcomponent you're using should also be memoized if it's re-rendering unnecessarily (though in your code, it's receiving a static proptitle="hiii bhh", so this shouldn't trigger a Home re-render) - You've set
Home.displayNamecorrectly, which helps with memoization debugging and React DevTools – nice touch there!
4. Update Expo Router to the Latest Stable Version
Older versions of Expo Router had edge cases with stack navigation where screens would be unexpectedly unmounted. Run this command to ensure you're on the latest stable build:
npx expo install expo-router react-native-screens react-native-safe-area-context
What to Expect After Fixing
Once you apply these changes:
- When you navigate to Details, you won't see the "Cleanup function called" log (Home stays mounted in the stack)
- When you navigate back to Home, you won't see "useEffect called home" or "Home screen rendered" logs (since the component was never unmounted)
- The Home screen will retain its state and avoid unnecessary re-renders/mounts
内容来源于stack exchange

