跳到主要内容

修复React Context报错

小林
后端开发工程师, 专注Go开发、微服务和云原生

在使用 React Context 时参照了官方的示例, 没想到报 render is not a function 错误, 找了一下发现是版本的问题

在使用 React Context 时, 使用了官方的这个示例

import Heading from './Heading.js';
import Section from './Section.js';

export default function Page() {
return (
<Section level={1}>
<Heading>Title</Heading>
<Section level={2}>
<Heading>Heading</Heading>
<Heading>Heading</Heading>
<Heading>Heading</Heading>
<Section level={3}>
<Heading>Sub-heading</Heading>
<Heading>Sub-heading</Heading>
<Heading>Sub-heading</Heading>
<Section level={4}>
<Heading>Sub-sub-heading</Heading>
<Heading>Sub-sub-heading</Heading>
<Heading>Sub-sub-heading</Heading>
</Section>
</Section>
</Section>
</Section>
);
}

报了如下错误

render is not a function
TypeError: render is not a function
at updateContextConsumer (webpack-internal:///./node_modules/react-dom/cjs/react-dom.development.js:21241:19)
at beginWork (webpack-internal:///./node_modules/react-dom/cjs/react-dom.development.js:21686:14)
at HTMLUnknownElement.callCallback (webpack-internal:///./node_modules/react-dom/cjs/react-dom.development.js:4164:14)
at Object.invokeGuardedCallbackDev (webpack-internal:///./node_modules/react-dom/cjs/react-dom.development.js:4213:16)
at invokeGuardedCallback (webpack-internal:///./node_modules/react-dom/cjs/react-dom.development.js:4277:31)
at beginWork$1 (webpack-internal:///./node_modules/react-dom/cjs/react-dom.development.js:27485:7)
at performUnitOfWork (webpack-internal:///./node_modules/react-dom/cjs/react-dom.development.js:26591:12)
at workLoopConcurrent (webpack-internal:///./node_modules/react-dom/cjs/react-dom.development.js:26577:5)
at renderRootConcurrent (webpack-internal:///./node_modules/react-dom/cjs/react-dom.development.js:26539:7)
at performConcurrentWorkOnRoot (webpack-internal:///./node_modules/react-dom/cjs/react-dom.development.js:25772:38)

用的官方示例, 没理由有问题啊. 找了一下, 原来 React 19 版本 <Context> 标签移除了 .Provider 后缀, 给开发者提供便利, 但是因为我用的还是 React 18 版本, 所以还是需要加上 .Provider

参考 React 18 版本的示例, 修改 Section.js

Section.js
import { LevelContext } from './LevelContext.js';

export default function Section({ level, children }) {
return (
<section className="section">
<LevelContext.Provider value={level}>
{children}
</LevelContext.Provider>
</section>
);
}