You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用useContext获取用户信息登出时出现user is null错误求助

问题排查:登出时触发 user is null 类型错误

错误信息

Uncaught TypeError: user is null
    children Animate.jsx:79
    Animate Animate.jsx:76

问题场景

通过useContext获取登录用户详情,登录状态下无报错,执行登出操作时控制台抛出上述错误,错误指向Animate.jsx第79行的if(user.email==object.email)代码。


问题根源

  1. Context状态不一致:Context.js中user初始值设为{}空对象,但Firebase的onAuthStateChanged在用户登出后会传入null,导致Context的value变为null,与初始状态类型不统一。
  2. 未做空值校验:Animate.jsx中直接访问user.email,当user变为null时,访问其属性会触发TypeError。

修复方案

1. 统一Context的user初始状态

修改Context.js中user的初始值为null,保持与登出后的状态一致:

// Context.js
const [user, setuser] = useState(null); // 将初始值从{}改为null

2. 在使用user的位置增加空值判断

在Animate.jsx的/MyRecipe路由逻辑中,先判断user是否存在,再访问其属性:

// Animate.jsx 中MyRecipe路由的map回调内
if(user && user.email === object.email){ // 增加user存在性校验
    console.log(user.email);
    // 后续返回RecipeCard的JSX代码保持不变
}

3. 强化Protected组件的拦截逻辑(推荐)

由于/MyRecipe路由已被Protected组件包裹,可在Protected组件中增加user空值判断,确保只有登录状态才渲染子组件,避免登出时的短暂状态异常:

// Protected.jsx 示例代码
import { useContext } from 'react';
import { Context } from '../Context';
import { Navigate } from 'react-router-dom';

export default function Protected({ children }) {
    const user = useContext(Context);
    if (!user) {
        return <Navigate to="/Login" replace />;
    }
    return children;
}

内容的提问来源于stack exchange,提问作者Mohd Zaid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 11:45:34