![](/img/trans.png)
[英]Window is undefined in Nextjs but values are needed in useState
[英]Window is undefined in NextJS + Tauri
我使用 Tauri 的appWindow
訪問appWindow.minimize()
、 appWindow.toggleMaximize()
和appWindow.close()
以創建自定義標題欄。
import { appWindow } from "@tauri-apps/api/window";
const CustomTitleBar = () => {
const hasLoaded = hasLoadedCSR(); // custom hook for checking if component has mounted using useEffect
if (typeof window === "undefined") return <></>; // 1st attempt to disable SSR for this component
if (!hasLoaded) return <></>; // 2nd attempt to disable SSR for this component
return (
<>
<div data-tauri-drag-region className="titlebar">
<button
className="titlebar-button"
id="titlebar-minimize"
onClick={() => {
console.log("Clicked");
appWindow.minimize();
}}
>
<img
src="https://api.iconify.design/mdi:window-minimize.svg"
alt="minimize"
/>
</button>
<button
className="titlebar-button"
id="titlebar-maximize"
onClick={() => appWindow.toggleMaximize()}
>
<img
src="https://api.iconify.design/mdi:window-maximize.svg"
alt="maximize"
/>
</button>
<button className="titlebar-button" id="titlebar-close">
<img
src="https://api.iconify.design/mdi:close.svg"
alt="close"
onClick={() => appWindow.close()}
/>
</button>
</div>
</>
);
};
export default CustomTitleBar;
我基本上做了 2 次嘗試來解決這個問題,因為我絕對認為這是由FabianLars在類似問題中提到的 SSR 引起的。
為了解決這個問題,我基本上使用dynamic
函數創建了另一個組件來強制CustomTitleBar
的 CSR。
import dynamic from "next/dynamic";
const DynamicCustomTitleBar = dynamic(() => import("./CustomTitleBar"), {
ssr: false,
});
export default DynamicCustomTitleBar;
我如何解決這個問題如下。
如果以及當我使用任何 @tauri-apps/api 導出時,我將它們包裝在一個組件中,然后使用不帶 ssr 的動態導入流導入該組件。 這主要是為了讓我的項目井井有條,因為我只是為我可能想從 tauri-apps/api 使用的每個 function 創建一個包裝器。
所以我會制作以下文件夾結構:
const TauriApiWrapComponent = dynamic(() => import("./TauriApiWrapComponent"), {
ssr: false,
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.