gpt4 book ai didi

reactjs - 在 Gatsby 中使用 document.cookie

转载 作者:行者123 更新时间:2023-12-04 12:37:35 25 4
gpt4 key购买 nike

我需要能够在我的 Gatsby 项目中设置和访问 cookie,并且我能够使用 this tutorial 获得一些可靠的设置.我正在构建一个设置 cookie 的钩子(Hook),并在整个站点中使用它。这就是助手完成后的样子。
使用-cookie.ts

import { useState, useEffect } from 'react';

const getItem = (key) =>
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, value, numberOfDays) => {
const now = new Date();

// set the time to be now + numberOfDays
now.setTime(now.getTime() + numberOfDays * 60 * 60 * 24 * 1000);
document.cookie = `${key}=${value}; expires=${now.toUTCString()}; path=/`;
};

/**
*
* @param {String} key The key to store our data to
* @param {String} defaultValue The default value to return in case the cookie doesn't exist
*/

export const useCookie = (key, defaultValue) => {
const getCookie = () => getItem(key) || defaultValue;
const [cookie, setCookie] = useState(getCookie());

const updateCookie = (value, numberOfDays) => {
setCookie(value);
setItem(key, value, numberOfDays);
};

return [cookie, updateCookie];
};
我将钩子(Hook)调用到一个组件中,如下所示:
DealerList.tsx
import React, { ReactNode, useEffect } from 'react';

import { Container } from 'containers/container/Container';
import { Section } from 'containers/section/Section';
import { Link } from 'components/link/Link';

import s from './DealerList.scss';
import { useCookie } from 'hooks/use-cookie';

interface DealerListProps {
fetchedData: ReactNode;
}

let cookie;

useEffect(() => {
cookie = useCookie();
}, []);


export const DealerList = ({ fetchedData }: DealerListProps) => {
const dealerInfo = fetchedData;
if (!dealerInfo) return null;

const [cookie, updateCookie] = useCookie('one-day-location', 'sacramento-ca');

return (
<>
<Section>
<Container>
<div className={s.list}>
{dealerInfo.map((dealer: any) => (
<div className={s.dealer} key={dealer.id}>
<div className={s.dealer__info}>
<h3 className={s.name}>
{dealer.company.name}
</h3>
<span className={s.address}>{dealer.address.street}</span>
<span className={s.city}>{dealer.address.city} {dealer.address.zip}</span>
</div>
<div className={s.dealer__contact}>
<span className={s.email}>{dealer.email}</span>
<span className={s.phone}>{dealer.phone}</span>
</div>
<div className={s.dealer__select}>
<Link
to="/"
className={s.button}
onClick={() => {
updateCookie(dealer.phone, 10);
}}
>
Select Location
</Link>
</div>
</div>
))}
</div>
</Container>
</Section>
</>
);
};
它适用于 gatsby develop我可以访问 cookie 的值并相应地更改显示的联系信息。但是,当我尝试构建或推送到 Netlify 时,出现此错误。 WebpackError: ReferenceError: document is not defined我知道这与 document.cookie 有关在第 4 行和第 17 行,但我正在努力弄清楚如何解决它。有什么建议?我是进口的 useEffect ,从我的研究来看,这与它有关,但我该怎么做才能让它正常工作?
提前致谢。

最佳答案

我做了更多的研究,我发现 this simple hook , 替换了 use-cookie.ts 中的代码有了这个,对其进行了一些修改(包括在下面),安装了 universal-cookie它似乎完美地工作。这是新代码:
使用-cookie.ts

import { useState } from 'react';
import Cookies from 'universal-cookie';

export const useCookie = (key: string, value: string, options: any) => {
const cookies = new Cookies();
const [cookie, setCookie] = useState(() => {
if (cookies.get(key)) {
return cookies.get(key);
}
cookies.set(key, value, options);
});

const updateCookie = (value: string, options: any) => {
setCookie(value);
removeItem(value);
cookies.set(key, value, options);
};

const removeItem = (key: any) => {
cookies.remove(key);
};

return [cookie, updateCookie, removeItem];
};
如果有人有更好的方法来做到这一点,请告诉我!

关于reactjs - 在 Gatsby 中使用 document.cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62905903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com