问题描述:
Error: Could not find the module "D:\code\learn\javascript\test-data-context\src\app\context\app-context.js#AppContext#Provider" in the React Client Manifest. This is probably a bug in the React Server Components bundler.
想用React Context做下用法验证,就使用NextJS创建了一个项目,编写了简单的Context代码用于验证
主要代码如下:
page.js
import styles from "./page.module.css";
import {AppContext} from "@/app/context/app-context";
import Header from "@/app/components/header";
import Main from "@/app/components/main";
export default function Home() {
return (
<AppContext.Provider value={{name: 'ZhanSan'}}>
<div className={styles.page}>
<Header/>
<Main/>
</div>
</AppContext.Provider>
);
}
app-context.js
"use client"
import React, {createContext} from "react";
export const AppContext = createContext({});
main.js
import {useContext} from "react";
import {AppContext} from "../context/app-context";
function Main() {
const app = useContext(AppContext);
return <>
<div> Main {app.name} </div>
<div><button onChange={() => {
app.name += 'changed'
}}>Change App Name</button></div>
</>
}
export default Main;
header.js
import {useContext} from "react";
import {AppContext} from "../context/app-context";
function Header() {
const app = useContext(AppContext);
return <div>Header {app.name} </div>
}
export default Header;
运行后页面报错:
无论怎么改写代码都不能解决,对比官方React官方文档并无出入,一时不得其解。
解决方法:
解决方法很简单:在page.js 最上面添加 'use client'
'use client'
import styles from "./page.module.css";
import {AppContext} from "@/app/context/app-context";
import Header from "@/app/components/header";
import Main from "@/app/components/main";
export default function Home() {
return (
<AppContext.Provider value={{name: 'ZhanSan'}}>
<div className={styles.page}>
<Header/>
<Main/>
</div>
</AppContext.Provider>
);
}
问题解决:
先前只考虑到React了,忽略了是在NextJS中使用React的。NextJS把我们的页面当成服务端渲染,React的Context API看来还没支持