Error: Could not find the module “AppContext#Provider“ in the React Client Manifest

问题描述:

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看来还没支持

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CoderFusionZhu

不要打赏太多哦!我喝速溶就行

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值