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

React Context Value始终返回undefined的问题排查与解决求助

React Context使用错误修正及解决方案

问题根源

  • 直接访问PromptContext.Provider.value完全错误:Provider是React组件,它的value是组件的props参数,不是挂载在Provider本身的静态属性,所以打印必然返回undefined。
  • generateRecipe是普通函数而非React组件:里面写的<PromptContext.Provider>只是创建了一个JSX元素,但既没有返回也没有渲染,根本不会把值注入到Context中。
  • Consumer用法错误:Consumer的回调参数就是Provider传递的value本身,你传的是字符串"hello",不需要再取test.value,直接用参数即可。

正确实现步骤

1. 定义并导出Context

在单独文件(比如PromptContext.js)中定义并导出Context,方便跨文件使用:

import { createContext } from 'react';

// 可设置默认值,也可留空
const PromptContext = createContext();

export default PromptContext;

2. 在父组件中用Provider包裹子组件

Provider必须放在React组件的渲染输出内,且包裹所有需要消费该Context的组件:

import PromptContext from './PromptContext';
import RecipeConsumer from './RecipeConsumer'; // 你的消费组件

function ParentComponent() {
  // 可动态设置value,比如从state中获取
  const providerValue = "hello";

  return (
    <PromptContext.Provider value={providerValue}>
      {/* 所有需要消费Context的组件都要放在Provider内部 */}
      <RecipeConsumer />
    </PromptContext.Provider>
  );
}

3. 在其他文件中消费Context

方式一:使用Consumer组件

import PromptContext from './PromptContext';

function RecipeConsumer() {
  return (
    <PromptContext.Consumer>
      {/* 回调参数就是Provider传递的value,直接使用 */}
      {(value) => <h1>{value}</h1>}
    </PromptContext.Consumer>
  );
}

export default RecipeConsumer;

方式二:使用useContext Hook(更简洁)

函数组件推荐用useContext替代Consumer:

import { useContext } from 'react';
import PromptContext from './PromptContext';

function RecipeConsumer() {
  const value = useContext(PromptContext);
  return <h1>{value}</h1>;
}

export default RecipeConsumer;

扩展:在函数中修改Context值

如果想通过generateRecipe修改Context的值,需要结合React state实现:

import { useState } from 'react';
import PromptContext from './PromptContext';

function ParentComponent() {
  const [contextValue, setContextValue] = useState("初始值");

  const generateRecipe = () => {
    const newValue = "hello";
    // 通过更新state来修改Context的值
    setContextValue(newValue);
    console.log(newValue);
    console.log("Generating recipe...");
  };

  return (
    <PromptContext.Provider value={contextValue}>
      <button onClick={generateRecipe}>生成食谱</button>
      <RecipeConsumer />
    </PromptContext.Provider>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 05:05:14