简体   繁体   English

react-cookie 无法设置过期或 maxAge

[英]react-cookie unable to set expires or maxAge

I cannot seem to set the expiration for a cookie with react-cookie... here is my setup:我似乎无法使用 react-cookie 设置 cookie 的过期时间...这是我的设置:

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

The following attempts have failed:以下尝试均失败:

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 continues to present: Chrome 继续呈现:

Expires
When the browsing session ends

It seems that Cookies from react-cookie has been moved to the universal-cookie package.似乎来自react-cookie Cookies已移至universal-cookie包中。 So the following should work:所以以下应该工作:

import Cookies from 'universal-cookie';

const cookies = new Cookies();
cookies.set('cookieName', {key: value}, {path: '/', expires: new Date(Date.now()+2592000)});

Example with expire after one year一年后过期示例

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,
});

Here you can see more on how to use Date.set https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear在这里你可以看到更多关于如何使用 Date.set https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear

A little late, but if anyone out there is still having trouble with this.有点晚了,但是如果有人在那里仍然遇到问题。 In universal-cookie try using the maxAge option instead of expires .在通用 cookie 中尝试使用maxAge选项而不是expires

Here's a snippet of how I got mine to work.这是我如何让我的工作的片段。

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

Being honest you're better off using the normal cookie setting stuff.老实说,您最好使用普通的 cookie 设置内容。 Info Here 信息在这里

You're gonna have to use document.cookie anyway to interact with your already set cookie right from loading anyways.无论如何,您将不得不使用document.cookie与您已经设置的 cookie 进行交互。 Here's a snippet of my code for that.这是我的代码片段。 Along with the useState hook for reference.连同 useState 钩子以供参考。

Like shown in this doc , document.cookie shows you a list of all cookies output like this.就像本文档中所示, document.cookie向您显示所有 cookie 输出的列表,如下所示。

cookieOne=1; cookieTwo=poopy; cookieThree=etc

So, write something like this out.所以,写出这样的东西。 Substituting "theme" for your cookie name.用“主题”代替您的 cookie 名称。 This code will give you that value.此代码将为您提供该值。

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

You'll get a string back no matter what, so if its a int or anything else convert appropriately.无论如何,你都会得到一个字符串,所以如果它是一个 int 或其他任何适当的转换。 Here's my useState hook with my cookie needing to be an int.这是我的 useState 钩子,我的 cookie 需要是一个 int。

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

Hope that helps whoever is still stuck!希望对仍然卡住的人有所帮助!

TLDR; TLDR;

Use maxAge instead of expires .使用maxAge而不是expires

Use document.cookie to check initial cookie value for state.使用document.cookie检查状态的初始 cookie 值。

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. (包括我自己)在添加 30 天或 2592000 秒的最大年龄之前,我让我的应用程序在 .set 方法中使用没有 maxAge 属性的通用 cookie 运行。 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.当我将 maxAge: 2592000 添加到我的 set cookie 方法时,浏览器说它仍然会在会话结束时过期。 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.对我来说,解决方法是清除开发工具 -> 应用程序 -> 存储 -> 清除站点数据中的应用程序数据,然后重新登录我的应用程序,并将 cookie 正确设置为在 30 天后过期。 For reference:以供参考:

cookies.set("loggedinUserId", response.data.userID, { path: '/', maxAge: 2592000 });

I've been trying to figure out what I was doing wrong and I think I found it.我一直在努力找出我做错了什么,我想我找到了。

First, some users are stating that maxAge property in the .set method is the solution.首先,一些用户指出.set方法中的maxAge属性是解决方案。 Well, this could work but if the user reloads the browser, the cookie will disappear and this would make no sense.好吧,这可行,但如果用户重新加载浏览器, cookie 将消失,这将毫无意义。

The solution is to play around with the expires property.解决方案是使用expires属性。 I did this:我这样做了:

import Cookies from "universal-cookie";

const cookies = new Cookies();
const expirationDate = new Date();

// (Just change 7 for the number of days you want to let this cookie exist)
expirationDate.setDate(expirationDate.getDate() + 7);

const cookieExists = cookies.get("myCookie");

if (!cookieExists) {
  cookies.set("myCookie", `ImTheValue`, { path: '/', expires: expirationDate });
}

As you can see, cookieExists makes the validation of the cookie easier.如您所见, cookieExists使 cookie 的验证更加容易。 If the cookie doesn't exist, it will create it.如果 cookie 不存在,它将创建它。 If it does, it won't set a new expiration date.如果是,则不会设置新的到期日期。

This would do the trick!这样就可以了!

I Hope this can be useful to anyone out there with the same problem I had.我希望这对遇到我遇到的同样问题的任何人都有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM