使用React上下文在Remix React中无法正常工作?
尽管在非混音项目中看到了此示例,但它似乎并没有用我实施的方式工作吗?
我在root.tsx
中有以下内容:
export const MyContext = createContext("default");
function Document({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<Meta />
<Links />
</head>
<body className="root-body">
<MyContext.Provider value="bonjour!">
<Header />
</MyContext.Provider>
{children}
<ScrollRestoration />
<Scripts />
<LiveReload />
<Footer />
</body>
</html>
);
}
export default function App() {
return (
<Document>
<Outlet />
</Document>
);
}
在我的&lt; header/&gt;
组件中我有:
import { useContext } from "react";
import { MyContext } from "~/root";
export const Header = () => {
const result = useContext(MyContext);
console.log(result);
return(null)
}
结果是“ deff”
是否印刷到控制台,但肯定从我的理解中应该是“ Bonjour”
?
我要去哪里?
Despite having seen working examples of this in non remix projects, it doesn't seem to work in the way I'm implementing it?
I have the following in root.tsx
:
export const MyContext = createContext("default");
function Document({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<Meta />
<Links />
</head>
<body className="root-body">
<MyContext.Provider value="bonjour!">
<Header />
</MyContext.Provider>
{children}
<ScrollRestoration />
<Scripts />
<LiveReload />
<Footer />
</body>
</html>
);
}
export default function App() {
return (
<Document>
<Outlet />
</Document>
);
}
In my <Header/>
component I have:
import { useContext } from "react";
import { MyContext } from "~/root";
export const Header = () => {
const result = useContext(MyContext);
console.log(result);
return(null)
}
The result is then that "default"
is printed to the console, but surely from my understanding it should be "bonjour"
?
Where am I going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
服务器控制台上的输出来自Remix SSR。似乎在服务器渲染过程中没有应用上下文。但是,它确实在水合后正确显示。不幸的是,这也导致水合错误(请参阅浏览器控制台)。
无论如何,这似乎很奇怪。我的理解是,您可以使用大多数挂钩服务器端(
useffect
和uselayouteffect
)。https://codesandbox.io/s/remix-remix-remix-remix-remix-cont-context-context-context-mzexmtext-mzexmtext-mzexmt
The output on the server console is from Remix SSR. It does appear that the context is not being applied during server rendering. However, it does show up correctly after hydration. Unfortunately it also results in hydration errors (see browser console).
Anyway, that does seem odd. My understanding is that you can use most hooks server side (except for
useEffect
anduseLayoutEffect
).https://codesandbox.io/s/remix-react-context-mzexmt