React中react-context-api多上下文传递给子组件的报错解决
解决React Context传递子组件时的'Cannot read properties of undefined (reading '_context')'错误
错误原因
- 循环导入:App组件导入DropDown,DropDown又从App导入Context,导致Context在DropDown中未被正确初始化,出现undefined。
- DropDown直接渲染Context对象,会显示
[object Object],无法正确展示内容。
修改步骤
1. 拆分Context到独立文件
创建contexts.js文件,将两个Context的定义移到这里,避免循环依赖:
import React from "react"; export const UserContext = React.createContext(); export const CartContext = React.createContext();
2. 修改App组件,从独立文件导入Context
import React, { useContext } from "react"; import DropDown from "./DropDown"; // 从独立文件导入Context import { UserContext, CartContext } from "./contexts"; function MyComponent() { const user = useContext(UserContext); const cart = useContext(CartContext); return ( <div> <h1>Hello, {user.name}!</h1> <h2>You have {cart.items.length} items in your cart.</h2> </div> ); } function App() { return ( <UserContext.Provider value={{ name: "John" }}> <CartContext.Provider value={{ items: ["Apple", "Banana"] }}> <MyComponent /> <DropDown /> </CartContext.Provider> </UserContext.Provider> ); } export default App;
3. 修改DropDown组件,从独立文件导入Context并正确渲染属性
import React, { useContext } from "react"; // 从独立文件导入Context,而非App组件 import { UserContext, CartContext } from "./contexts"; export default function DropDown() { const userValue = useContext(UserContext); const cartValue = useContext(CartContext); console.log(userValue, cartValue); return ( <> <h1>Hello, {userValue.name}!</h1> <p>You have {cartValue.items.length} items in your cart:</p> <ul> {cartValue.items.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> </> ); }
说明
- 拆分Context到独立文件彻底解决了循环导入导致的Context实例未初始化问题,保证两个组件使用的是同一个Context实例。
- 修改DropDown的渲染逻辑,和MyComponent一致读取Context对象的具体属性,确保内容正确显示。
内容的提问来源于stack exchange,提问作者Sougata Mukherjee
相关产品推荐
相关产品推荐

