React 开发 Context 问题:Uncaught ReferenceError: Cannot access ‘MyContext‘ before initialization

张开发
2026/4/11 11:51:57 15 分钟阅读

分享文章

React 开发 Context 问题:Uncaught ReferenceError: Cannot access ‘MyContext‘ before initialization
Parent 组件import { Component, createContext } from react; import Child from ../Child; import ./index.css; const MyContext createContext(); const { Provider } MyContext; export { MyContext }; export class Parent extends Component { state { username: tom, age: 18 }; render() { const { username, age } this.state; return ( div classNameparent h3Parent/h3 Provider value{{ username, age }} Child / /Provider /div ); } }.parent{width:500px;background-color:orange;padding:8px;}Child 组件import { Component } from react; import Grand from ../Grand; import ./index.css; export default class Child extends Component { render() { return ( div classNamechild h3Child/h3 Grand / /div ); } }.child{width:100%;background-color:skyblue;padding:8px;}Grand 组件import { Component } from react; import ./index.css; import { MyContext } from ../Parent; export default class Grand extends Component { static contextType MyContext; render() { const { username, age } this.context; return ( div classNamegrand h3Grand/h3 divusername: {username}/div divage: {age}/div /div ); } }.grand{width:100%;background-color:gray;padding:8px;}在 React 开发中上述代码出现如下错误信息Uncaught ReferenceError: Cannot access MyContext before initialization问题原因这个是模块加载顺序问题当Grand.jsx执行import { MyContext } from ../Parent时Parent.jsx刚开始加载还没有执行到const MyContext createContext();处理策略将 Context 单独抽离import{createContext}fromreact;constMyContextcreateContext();exportdefaultMyContext;Parent 组件import { Component } from react; import MyContext from ../../context; import Child from ../Child; import ./index.css; export class Parent extends Component { state { username: tom, age: 18 }; render() { const { username, age } this.state; return ( div classNameparent h3Parent/h3 MyContext.Provider value{{ username, age }} Child / /MyContext.Provider /div ); } }Child 组件import { Component } from react; import Grand from ../Grand; import ./index.css; export default class Child extends Component { render() { return ( div classNamechild h3Child/h3 Grand / /div ); } }Grand 组件import { Component } from react; import ./index.css; import MyContext from ../../context; export default class Grand extends Component { static contextType MyContext; render() { const { username, age } this.context; return ( div classNamegrand h3Grand/h3 divusername: {username}/div divage: {age}/div /div ); } }

更多文章