7

我似乎无法使用 react-cookie 设置 cookie 的过期时间......这是我的设置:

import { Cookies } from 'react-cookie'
const cookies = new Cookies()
import moment from 'moment'

以下尝试失败:

cookies.set('cookieName', {key: value}, {path: '/', expires: new Date(Date.now()+2592000)})
cookies.set('cookieName', {key: value}, {path: '/', expires: moment().add(30, "days")})
cookies.set('cookieName', {key: value}, {path: '/', maxAge: 2592000})

Chrome 继续呈现:

Expires
When the browsing session ends
4

4 回答 4

14

似乎Cookiesfromreact-cookie已移至universal-cookie包中。所以以下应该工作:

import Cookies from 'universal-cookie';

const cookies = new Cookies();
cookies.set('cookieName', {key: value}, {path: '/', expires: new Date(Date.now()+2592000)});
于 2017-12-17T23:28:34.167 回答
4

一年后到期的示例

import Cookies from 'universal-cookie';

const cookies = new Cookies();
const current = new Date();
const nextYear = new Date();

nextYear.setFullYear(current.getFullYear() + 1);

cookies.set('cookieName', true, {
    path: '/',
    expires: nextYear,
});

在这里你可以看到更多关于如何使用 Date.set https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear

于 2018-05-23T22:24:19.567 回答
2

有点晚了,但如果有人仍然有这个问题。在 Universal-cookie 中尝试使用maxAge选项而不是expires.

这是我如何让我的工作的片段。

cookies.set("theme", 0, {
    path: "/",
    maxAge: 1000000
});

老实说,您最好使用普通的 cookie 设置内容。信息在这里

无论如何,您将不得不使用document.cookie无论如何与您已经设置的 cookie 进行交互。这是我的代码片段。连同 useState 挂钩供参考。

如本文档所示,document.cookie向您显示所有 cookie 输出的列表,如下所示。

cookieOne=1; cookieTwo=poopy; cookieThree=etc

所以,写出这样的东西。将“主题”替换为您的 cookie 名称。此代码将为您提供该值。

const docThemeCookie = document.cookie
  .split("; ")
  .find((row) => row.startsWith("theme"))
  .split("=")[1];

无论如何,你都会得到一个字符串,所以如果它是一个 int 或其他任何适当的转换。这是我的 useState 钩子,我的 cookie 需要是一个 int。

const [theme, setTheme] = useState(parseInt(docThemeCookie, 10));

希望对仍然卡住的人有所帮助!

TLDR;

使用maxAge而不是expires.

用于document.cookie检查状态的初始 cookie 值。

于 2020-08-09T22:55:57.730 回答
0

Ok, so this may be a simple solution for some of you coming to this thread. (Myself included) I had my app running with universal-cookies without a maxAge property in the .set method before adding a max age of 30 days or 2592000 seconds. When I added maxAge: 2592000 to my set cookie method the browser said that it was still going to expire at the end of the session. The fix for me was to clear the app data in the Dev tools -> Application -> Storage -> Clear Site Data then re log in to my app and the cookies were set to expire in 30 days correctly. For reference:

cookies.set("loggedinUserId", response.data.userID, { path: '/', maxAge: 2592000 });
于 2021-04-07T16:40:03.120 回答