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

Next.js项目中useContext Hook出现undefined错误,求问题排查

Next.js useContext 出现undefined错误的解决方法

核心错误

你在about.js里犯了一个关键错误——把封装Context的组件UseContexthere传给了useContext(),但实际上应该传入的是你创建的UserContext对象。

问题根源

在useContext/useContexthere.js中,UserContext = createContext()才是真正的Context对象,UseContexthere只是一个封装了UserContext.Provider的组件。但你在about.js中错误地将组件传给了useContext(),导致获取到的user为undefined,访问user.name自然会报错。

修正步骤

1. 导出Context对象

修改useContext/useContexthere.js,导出创建好的UserContext,让其他组件可以导入使用:

import React, { createContext, useContext} from 'react';

// 导出UserContext
export const UserContext = createContext();

const UseContexthere = ({children}) => {
    const biodata = {
        name : "Manish",
        profession : "Coder & Rapper",
        age : 25
    }
  return (
    <UserContext.Provider value={{biodata}}>
        {children}
    </UserContext.Provider>
  )
}

export default UseContexthere;

2. 正确使用Context

修改about.js,导入UserContext而非组件,同时注意Context值的结构(你传入的是{biodata}对象,需要先取出biodata属性):

import React, {useContext} from 'react';
// 导入正确的UserContext
import { UserContext } from './useContext/useContexthere';

const About = () => {
    // 解构获取Context中的biodata
    const { biodata } = useContext(UserContext);
  return (
    <div>
        <div>
            <h3>Following data is coming through useContext Hook</h3>
            <p>Hey my name is {biodata.name}</p>
            <p>Profession: {biodata.profession}</p>
            <p>Age: {biodata.age}</p>
        </div>
    </div>
  )
}

export default About

额外说明

  • useContext()的参数必须是createContext()返回的Context对象,不能是封装Provider的组件。
  • 你在Provider中传入的value是{biodata},所以获取到的Context值是一个包含biodata属性的对象,必须先取出该属性才能访问内部的具体字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 12:05:26