React Navigation调用navigation.navigate报TypeError未定义对象问题求助
报错原因排查
setTimeout直接写在函数组件顶层作用域,没有用useEffect钩子包裹。函数组件每次渲染时都会执行顶层代码,此时如果组件还未完成挂载、navigationprop 还未被 react-navigation 正确注入,就会触发navigation为 undefined 的报错,同时多次重渲染还会生成多个重复定时器,存在内存泄漏风险。- 没有添加定时器清理逻辑,若组件在3秒内卸载,定时器回调仍然会执行,此时导航实例已经销毁也会触发同类报错。
修复方案
你可以选择任意一种方式修改 AccountScreen 代码即可解决问题:
方案1:基于props的navigation属性修复
import React, { useEffect } from "react"; import { AccountBackground, AccountCover, Title} from "../components/account.styles"; import { MaterialIcons } from "@expo/vector-icons"; export const AccountScreen = ({ navigation }) => { useEffect(() => { const timer = setTimeout(() => { // 加可选链判断兜底,避免navigation未初始化时报错 navigation?.navigate("Login"); }, 3000); // 组件卸载时清理定时器 return () => clearTimeout(timer); }, [navigation]); return ( <AccountBackground> <AccountCover /> <Title>Meals To Go</Title> <MaterialIcons name="navigate-next" size={48} color="black" /> </AccountBackground> ); };
方案2:使用useNavigation钩子获取导航实例(更稳妥)
无需依赖props传递,直接从react-navigation全局获取导航实例:
import React, { useEffect } from "react"; import { useNavigation } from "@react-navigation/native"; import { AccountBackground, AccountCover, Title} from "../components/account.styles"; import { MaterialIcons } from "@expo/vector-icons"; export const AccountScreen = () => { const navigation = useNavigation(); useEffect(() => { const timer = setTimeout(() => { navigation.navigate("Login"); }, 3000); return () => clearTimeout(timer); }, [navigation]); return ( <AccountBackground> <AccountCover /> <Title>Meals To Go</Title> <MaterialIcons name="navigate-next" size={48} color="black" /> </AccountBackground> ); };
内容的提问来源于stack exchange,提问作者Harish Kumar
相关产品推荐
相关产品推荐

