React Native函数组件中FlatList跳转触发Invalid hook call错误求助
解决React Native中FlatList点击项跳转时的Hook调用错误
错误原因
你遇到的Error: Invalid hook call. Hooks can only be called inside of the body of a function component.错误,本质是违反了React Hook的核心规则:Hook只能在函数组件的顶层作用域调用,不能在事件回调、嵌套函数或者普通函数内部使用。
你的代码中,useNavigate被直接写在Pressable的onPress回调函数里,同时renderItem是独立于NoteList组件的普通函数,这两处都不符合Hook的调用要求。
解决方案
- 在
NoteList函数组件的顶层作用域调用useNavigate,获取导航函数 - 将
renderItem定义在NoteList组件内部,让它能访问到顶层的导航函数 - 在
onPress回调中直接调用获取到的导航函数,而非再次调用useNavigate
修正后的代码
import { FlatList, Pressable, StyleSheet, View } from "react-native" import { useNavigate } from "react-router-native" import theme from "../theme" import Text from "./Text" const styles = StyleSheet.create({ separator: { height: 10, backgroundColor: theme.colors.background, }, item: { padding: 8, backgroundColor: "white", }, }) const ItemSeparator = () => <View style={styles.separator} /> const NoteList = ({ notes }) => { // 在组件顶层获取导航函数 const navigate = useNavigate(); // 组件内部定义renderItem,可直接访问navigate const renderItem = ({ item }) => ( <View style={styles.item}> <Pressable onPress={() => navigate(`/${item.id}`)}> <Text fontWeight="bold" fontSize="subheading"> {item.title} </Text> <Text>{item.body}</Text> </Pressable> </View> ) return ( <FlatList data={notes} ItemSeparatorComponent={ItemSeparator} renderItem={renderItem} keyExtractor={(item) => item.id} /> ) } export default NoteList;
额外注意事项
- 确保
NoteList组件被正确包裹在react-router-native的路由提供者(如NativeRouter)内部,否则useNavigate无法正常获取路由上下文 - 所有React Hook都必须严格遵循调用规则:只能在函数组件或自定义Hook的顶层调用,不能出现在条件判断、循环、嵌套函数或事件回调中
内容的提问来源于stack exchange,提问作者George Garman
相关产品推荐
相关产品推荐

