我正在使用一个自定义挂钩来设置、编辑和删除Gatsby网站上的cookie:
使用cookie.ts
import { useState } from 'react';
const getItem = (key: string) => {
if (typeof document !== undefined) {
document.cookie.split('; ').reduce((total, currentCookie) => {
const item = currentCookie.split('=');
const storedKey = item[0];
const storedValue = item[1];
return key === storedKey ? decodeURIComponent(storedValue) : total;
}, '');
}
};
const setItem = (key: string, value: string | boolean, numberOfDays: number) => {
const now = new Date();
now.setTime(now.getTime() + numberOfDays * 60 * 60 * 24 * 1000);
if (typeof document !== undefined) {
document.cookie = `${key}=${value}; expires=${now.toUTCString()}; path=/`;
}
};
export const useCookie = (key: string, defaultValue: string | boolean | any) => {
const getCookie = () => (getItem(key), defaultValue);
const [cookie, setCookie] = useState(getCookie());
const updateCookie = (value: string, numberOfDays: number) => {
setCookie(value);
setItem(key, value, numberOfDays);
};
return [cookie, updateCookie];
};
我在这样的组件中使用它:
const [initialCookieValue, updateCookieValue] = useCookie('cookie', false);
然而,尽管使用if (typeof document !== undefined)
检查了对document
的所有引用,我的网站仍然在使用WebpackError: ReferenceError: document is not defined
进行构建。我不知道我做错了什么,也不知道如何修复它,但我知道,如果我去掉钩子,错误就会消失。
有什么想法吗?
检查未定义为字符串'undefined'
。
if (typeof document !== 'undefined')
应用于您的代码:
import { useState } from 'react';
const getItem = (key: string) => {
if (typeof document !== 'undefined') {
document.cookie.split('; ').reduce((total, currentCookie) => {
const item = currentCookie.split('=');
const storedKey = item[0];
const storedValue = item[1];
return key === storedKey ? decodeURIComponent(storedValue) : total;
}, '');
}
};
const setItem = (key: string, value: string | boolean, numberOfDays: number) => {
const now = new Date();
now.setTime(now.getTime() + numberOfDays * 60 * 60 * 24 * 1000);
if (typeof document !== 'undefined') {
document.cookie = `${key}=${value}; expires=${now.toUTCString()}; path=/`;
}
};
export const useCookie = (key: string, defaultValue: string | boolean | any) => {
const getCookie = () => (getItem(key), defaultValue);
const [cookie, setCookie] = useState(getCookie());
const updateCookie = (value: string, numberOfDays: number) => {
setCookie(value);
setItem(key, value, numberOfDays);
};
return [cookie, updateCookie];
};