我正在使用自定义钩子来设置,编辑和删除Gatsby网站上的cookie:
use-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);
但是,尽管使用document
检查了对if (typeof document !== undefined)
的所有引用,但我的网站仍然无法使用WebpackError: ReferenceError: document is not defined
构建。我不知道我在做什么错,或者如何解决它,但是我知道如果删除钩子,错误就会消失。
有什么想法吗?
答案 0 :(得分:0)
检查未定义为字符串'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];
};