Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/469.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在_document.js和Next.js上的页面之间共享React上下文?_Javascript_Reactjs_Next.js_Tailwind Css - Fatal编程技术网

Javascript 如何在_document.js和Next.js上的页面之间共享React上下文?

Javascript 如何在_document.js和Next.js上的页面之间共享React上下文?,javascript,reactjs,next.js,tailwind-css,Javascript,Reactjs,Next.js,Tailwind Css,假设我有这样的背景: export const ThemeContext = createContext(); export function ThemeWrapper({ children }) { const sharedState = { darkMode: false, }; return ( <ThemeContext.Provider value={sharedState}> {children} </ThemeC

假设我有这样的背景:

export const ThemeContext = createContext();

export function ThemeWrapper({ children }) {
  const sharedState = {
    darkMode: false,
  };

  return (
    <ThemeContext.Provider value={sharedState}>
      {children}
    </ThemeContext.Provider>
  );
}

export function useThemeContext() {
  return useContext(ThemeContext);
}
现在,我还想从页面访问此上下文:

import { useThemeContext } from "../context/theme";

const SomePage = () => {
  const theme = useThemeContext();

  console.log("theme", theme);

  return (
    <div>Hi, I'm a page</div>
  );
};
从“./context/theme”导入{useThemeContext};
常量SomePage=()=>{
const theme=useThemeContext();
console.log(“主题”,主题);
返回(
嗨,我是佩奇
);
};
\u document.js
首次加载页面时,会在Next.js控制台上注销
主题{darkMode:false}
,但每次导航到Chrome控制台时,都会在Chrome控制台上注销
未定义主题

有什么建议吗


我需要根据上下文在
html
标记上切换一些类。试图。

包装
\u文档
,包装器
不会让您访问页面内的上下文(可能是因为),您需要包装
\u应用程序
。只需注意,
\u文档
不会在上下文状态更改时重新呈现


对于此特定用例,另一种选择是使用。

那么新页面是否包装在主题包装器中?请尝试在主题包装器中包装Main,而不是包装文档。当您从next包装本机文档时,我感觉可能不起作用。您也可以尝试创建一个自定义应用程序并在其中添加上下文包装器。您应该在自定义应用程序中使用ThemeWrapper,而不是Document@Keith不,我需要吗?我以为包装文档可以让我在树下的任何地方都可以访问。
import { useThemeContext } from "../context/theme";

const SomePage = () => {
  const theme = useThemeContext();

  console.log("theme", theme);

  return (
    <div>Hi, I'm a page</div>
  );
};