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>); } }
修复说明
- 补全
AppContext类构造函数的闭合大括号,确保render方法正确挂载到组件类上,Provider能正常渲染。 - 修正Provider value对象的语法错误,移除属性末尾的分号。
- 调整Consumer的函数参数写法,使用正确的解构语法获取context值。
- 补充App组件中缺失的React Hooks导入,避免运行时错误。
内容的提问来源于stack exchange,提问作者smitchelluk
相关产品推荐
相关产品推荐

