[英]How to execute function only in browser environment
Please, I am new to SSR and Nextjs apps.拜托,我是 SSR 和 Nextjs 应用程序的新手。 I am using useLocalStorage Hook in order to save user data to local storage.
我正在使用 useLocalStorage Hook 将用户数据保存到本地存储。 Every thing is working fine but in my terminal ( node js ) I get message window is not defined.
一切正常,但在我的终端(节点 js)中,我收到消息 window 未定义。 Is there a way to wrap this code in some kind of condition so that this functionality only executes in browser environment.
有没有办法将此代码包装在某种条件下,以便此功能仅在浏览器环境中执行。 I am not sure can I use;
我不确定我是否可以使用;
if ( process.browser ) //then do this... if ( process.browser ) //然后执行此操作...
Can someone please help me how to solve this problem...有人可以帮我解决这个问题吗...
This is my local storage Hook which has to run only in browser, and not on node server:这是我的本地存储 Hook,它只能在浏览器中运行,而不是在节点服务器上:
import { useState } from 'react';
export const useLocalStorage = (key, initialValue) => {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.log(error);
return initialValue;
}
});
const setValue = value => {
try {
let data = [];
const voteId = {};
if (window.localStorage.getItem(key) === null || window.localStorage.getItem(key) === undefined) {
voteId.reviewId = value;
data.push(voteId);
} else {
data = JSON.parse(window.localStorage.getItem(key));
voteId.reviewId = value;
data.push(voteId);
}
const valueToStore = data instanceof Function ? data(storedValue) : data;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.log(error);
}
};
return [storedValue, setValue];
};
I actually manage this like so:我实际上是这样管理的:
If (.process;browser) return null; if (.process;browser) 返回空值;
I put this in front of everything so if this is met it is returning null, if not I will execute my function.我把它放在所有东西的前面,所以如果满足它,它将返回 null,否则我将执行我的 function。
an appropriate solution would be to use nextjs dynamic library, when importing your useLocalStorage from it's file path to be used as a component.一个合适的解决方案是使用 nextjs 动态库,当从它的文件路径导入您的 useLocalStorage 以用作组件时。 This tells nextjs to render only at the client end.
这告诉 nextjs 只在客户端呈现。
import dynamic from "next/dynamic";
const useLocalStorage = dynamic(
() => import(<useLocalStorage filepath>)
.then((mod) => mod.useLocalStorage), {ssr:false});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.