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

ReactJS中Provider传值给Consumer时props返回undefined问题

React Context 传递值为 undefined 的问题排查与修复

问题现象

使用React Context的Provider向下游Consumer传递值时,Consumer获取到的userName始终为undefined,无法正常渲染。

代码中的错误点分析

1. AppContext.tsx:类组件构造函数未闭合,render方法被错误嵌套

原代码中AppContext类的constructor方法缺失闭合的},导致render方法被包含在构造函数内部,组件无法正确渲染Provider,这是核心问题。

2. AppContext.tsx:Provider value对象中的语法错误

对象字面量属性末尾错误使用分号;,单属性场景下可直接省略符号,多属性时需用逗号,分隔。

3. TopBar.tsx:Consumer的函数参数写法错误

Consumer的子元素是一个函数,参数解构时错误使用两层大括号{{ userName }},正确写法应为({ userName })。

4. App.tsx:未导入useState和useEffect

函数组件中使用了useState和useEffect但未从React导入,会导致运行时错误。

修正后的代码

AppContext.tsx

import * as React from 'react';
import { App } from './App';

interface iHigherStateOfContextProps {
  username: string;
}

export const higherStateOfContext = React.createContext({} as iHigherStateOfContextProps);

interface IAppContextProps {}

interface IAppContextState {
  userName: string;
}

export class AppContext extends React.Component<IAppContextProps, IAppContextState> {
  constructor(props: IAppContextProps) {
    super(props);
    this.state = {
      userName: "Some Name"
    };
  }

  render() {
    return (
      <div>
        <higherStateOfContext.Provider value={{
          userName: this.state.userName
        }}>
          <App />
        </higherStateOfContext.Provider>
      </div>
    );
  }
}

App.tsx

import * as React from 'react';
import { useState, useEffect } from 'react';
import TopNavigation from './components/Navigation/TopBar';

export const App = function (props: {}) { 
    const [appTitle, setAppTitle] = useState<string>("App Name");
    useEffect(() => {}, []); 

    return (
        <div>
            {appTitle}
            <TopNavigation />
        </div>
    );
}

TopBar.tsx

import * as React from 'react';
import { higherStateOfContext } from '../../AppContext';

const Navigation = () => {
    return (
        <higherStateOfContext.Consumer>
            {({ userName }) => (
                <TopBar userName={userName} />
            )}
        </higherStateOfContext.Consumer>
    );
}

export default Navigation;

interface ITopBarProps {
    userName: string;
}

interface ITopsBarState {}

class TopBar extends React.Component<ITopBarProps, ITopsBarState> {
    constructor(props: ITopBarProps) {
        super(props);
        this.state = {};
    }

    render() {
        return (<div>{this.props.userName}</div>);
    }
}

修复说明

  1. 补全AppContext类构造函数的闭合大括号,确保render方法正确挂载到组件类上,Provider能正常渲染。
  2. 修正Provider value对象的语法错误,移除属性末尾的分号。
  3. 调整Consumer的函数参数写法,使用正确的解构语法获取context值。
  4. 补充App组件中缺失的React Hooks导入,避免运行时错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 12:02:15