React Native使用useContext取isAuthenticated报undefined错误咨询
报错原因&修复方案
1. Context Provider 缺失对应字段
你在AuthenticationContextProvider的value中只导出了user、isLoading、error、onLogin四个属性,并没有定义isAuthenticated字段,直接从Context返回值里解构这个不存在的属性,自然会触发undefined报错。
你可以直接用已有的user字段判断认证状态:用户登录成功后user不为null,对应就是已认证状态。
2. 组件未包裹在Context Provider作用域内
如果修复字段后仍然报错,请确认你的根组件是否把Navigation组件包裹在AuthenticationContextProvider内部。不在Provider作用域内的组件无法正常获取Context值,拿到的是createContext时的默认空值,也会触发同类报错。
具体修改代码
导航组件修改
把解构isAuthenticated的逻辑改成判断user是否存在:
import React, { useContext } from "react"; import { NavigationContainer } from "@react-navigation/native"; import { AppNavigator } from "./app.navigator"; import { AccountNavigator } from "./account.navigator"; import { AuthenticationContext } from "../../services/authentication/authentication.context"; export const Navigation = () => { const { user } = useContext(AuthenticationContext); // 用user是否非空判断认证状态 const isAuthenticated = !!user; return ( <NavigationContainer> {isAuthenticated ? <AppNavigator /> : <AccountNavigator />} </NavigationContainer> ); };
根组件配置示例
确保入口根组件正确包裹Provider:
import { AuthenticationContextProvider } from "./src/services/authentication/authentication.context"; import { Navigation } from "./src/infrastructure/navigation"; export default function App() { return ( <AuthenticationContextProvider> <Navigation /> </AuthenticationContextProvider> ); }
如果需要保留isAuthenticated字段直接使用,也可以直接在Provider的value里添加isAuthenticated: !!user,导航组件就不用额外做判断。
内容的提问来源于stack exchange,提问作者user16645351
相关产品推荐
相关产品推荐

