组件DidMount和Docusaurus出现问题



目前,我正在使用Docusaurus构建一个react应用程序,但在构建该应用程序时遇到了问题。错误信息显示:

[0] [ERROR] Docusaurus Node/SSR could not render static page with path /adminTools because of following error:
[0] ReferenceError: window is not defined
[0]     at Object.50671 (main:136486:44)
[0]     at __webpack_require__ (main:224909:42)
[0]     at Object.389 (main:136493:18)
[0]     at __webpack_require__ (main:224909:42)
[0]     at Module.95191 (main:58341:32)
[0]     at __webpack_require__ (main:224909:42)
[0]     at main:12784:4156
[0] [INFO] It looks like you are using code that should run on the client-side only.
[0] To get around it, try using `<BrowserOnly>` (https://docusaurus.io/docs/docusaurus-core/#browseronly) or `ExecutionEnvironment` (https://docusaurus.io/docs/docusaurus-core/#executionenvironment).
[0] It might also require to wrap your client code in `useEffect` hook and/or import a third-party library dynamically (if any).
[0] ✔ Server: Compiled with some errors in 28.91s
[0] 
[0] 
[0] Error: Server-side rendering fails due to the error above.

我认为这是我的adminTools组件的问题,因为我使用它们中的axios请求来更新我的componentDidMount函数中的状态。我认为这是错误的,不确定为什么,希望有人能帮我解决这个问题!我并不是100%了解生命周期,这就是为什么我要求澄清我做错了什么。

这也可能是一个网络包问题,但我再次不确定。

感谢您的帮助!

谢谢。

我解决了它!经过一番查看,我偶然发现了这篇溢出文章:React build-参考错误:Window未定义-如何仅在客户端上运行

这个人也有类似的问题,我发现通过使用loadable(((,我能够解决这个问题。

查看他们的文档!可加载文档

componentWillUnmount() {
if(typeof window !== 'undefined'){
window.location.reload();
}
}

要在开发和构建中解决这个问题,应该添加以下条件Root组件中的if (typeof window !== "undefined")

组件呈现在React树的最顶部,位于主题上方,并且从不卸载。它是添加不应在导航(用户身份验证状态、购物车状态…(中重新初始化的有状态逻辑的理想场所。阅读本文了解更多详细信息。

因此在src/theme下创建Root.js并在此处添加逻辑:

src/theme/Root.js

import React from "react";
export default function Root({ children }) {
if (typeof window !== "undefined") {
return (
<>
{children}
</>
);
}
return null;
}

像这样将彻底摆脱这个问题

最新更新