React Native使用useNavigation触发Invalid Hook Call错误求助
核心原因及对应解决方案
1. 组件未处于导航器上下文内
useNavigation钩子依赖React Navigation的上下文环境,你的HomeScreen必须被包裹在NavigationContainer内部的导航栈中,否则子组件无法获取导航上下文,触发钩子调用错误。
解决步骤:
检查项目入口文件(如App.js),确保导航结构正确:
import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import HomeScreen from './HomeScreen'; import ProductDetailsScreen from './ProductDetailsScreen'; const Stack = createStackNavigator(); export default function App() { return ( <NavigationContainer> <Stack.Navigator initialRouteName="Home"> <Stack.Screen name="Home" component={HomeScreen} /> <Stack.Screen name="Product_Details" component={ProductDetailsScreen} /> </Stack.Navigator> </NavigationContainer> ); }
2. FlatList的renderItem写法不规范
当前HomeScreen中直接将ProductCard赋值给renderItem,虽能传递props,但可能导致组件上下文异常。需改为显式返回组件的标准写法:
修改HomeScreen中的FlatList部分:
<FlatList ListHeaderComponent={/* 原有代码不变 */} data={products} // 替换原renderItem renderItem={({ item }) => <ProductCard item={item} />} numColumns={2} contentContainerStyle={{ paddingBottom: 25, }} />
3. 依赖版本不兼容
React与React Navigation版本不匹配也会触发钩子错误,可检查package.json中的依赖版本,确保@react-navigation/native、@react-navigation/stack等包版本一致,且与React Native版本兼容。
重新安装依赖:
npm install @react-navigation/native @react-navigation/stack npx pod-install # iOS平台执行此命令
备选方案:通过props传递navigation
若上述方法无效,可在HomeScreen中获取navigation后通过props传递给ProductCard:
- 修改HomeScreen:
import { useNavigation } from '@react-navigation/native'; const HomeScreen = () => { const navigation = useNavigation(); const [products, setProducts] = useState(data.products); const [selectedCategory, setSelectedCategory] = useState(null); return ( <ScrollView contentContainerStyle={styles.container}> <FlatList ListHeaderComponent={/* 原有代码不变 */} data={products} renderItem={({ item }) => <ProductCard item={item} navigation={navigation} />} numColumns={2} contentContainerStyle={{ paddingBottom: 25 }} /> </ScrollView> ); };
- 修改ProductCard:
const ProductCard = ({ item, navigation }) => { // 移除const navigation = useNavigation(); return ( <TouchableOpacity onPress={() => { navigation.navigate('Product_Details', { item }); }} style={styles.container} > {/* 原有UI代码不变 */} </TouchableOpacity> ); };
内容的提问来源于stack exchange,提问作者Muhammad Daniyal Arab
相关产品推荐
相关产品推荐

