React-Navigation嵌套导航报错:Maximum depth exceeded 求助
问题分析
你遇到的Maximum update depth exceeded错误,核心原因是在ConsumerAppScreen函数组件内部重复创建导航器与子组件。每次ConsumerAppScreen渲染时,内部的DetailsScreen、SettingsScreen、SettingsStackScreen以及createNativeStackNavigator()都会被重新定义,这会让React Navigation的导航器检测到组件/配置发生变化,触发重新渲染,最终形成无限循环。
解决方案
将所有嵌套的子组件、导航器定义移到ConsumerAppScreen外部,避免每次渲染时重新创建这些内容:
修改后的ConsumerAppScreen代码:
const Tab = createBottomTabNavigator(); // 导航器与子组件移至外部,避免重复创建 const SettingsStack = createNativeStackNavigator(); function DetailsScreen() { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Details!</Text> </View> ); } function SettingsScreen({ navigation }) { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Settings screen</Text> <Button title="Go to Details" onPress={() => navigation.navigate('Details')} /> </View> ); } function SettingsStackScreen() { return ( <SettingsStack.Navigator> <SettingsStack.Screen name="Settings" component={SettingsScreen} /> <SettingsStack.Screen name="Details" component={DetailsScreen} /> </SettingsStack.Navigator> ); } export const ConsumerAppScreen = () => { const { t, i18n } = useTranslation(); return ( <Tab.Navigator initialRouteName="Settings" tabBar={(props) => <ConsumerTabBar {...props} />} > <Tab.Screen name="Settings" component={SettingsStackScreen} options={{ icon: require("../../assets/dashboard-icon.png"), title: t('Settings') }} /> </Tab.Navigator> ) }
额外提示:如果ConsumerTabBar是自定义组件,需检查它的props依赖是否稳定,避免传递每次渲染都会变化的对象或函数,防止引发额外的不必要更新。
内容的提问来源于stack exchange,提问作者M_K
相关产品推荐
相关产品推荐

