React Cookie + ReactJS:如何设置cookie的到期时间? [英] React Cookie + ReactJS: How to set expiration time for a cookie?

查看:1258
本文介绍了React Cookie + ReactJS:如何设置cookie的到期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ReactJS项目中,目前我正在保存cookie,如 cookie.save('token',received_token,{path:'/'}); 并检索它从本地存储像这样: cookie.load('token');

In my ReactJS project, currently I am saving the cookie like cookie.save('token', received_token, { path: '/'} ); and retrieving it from the local storage like so: cookie.load('token');.

所以我想知道,是一种在 .save()收到令牌时设置到期时间的方法,一旦过期,会自动将其从本地存储中删除吗?

So I was wondering, is a way to set expiration time when .save() the token received, and once expired, automatically have it remove itself from the local storage?

谢谢你,并会在投票结束时接受答案。

Thank you and will accept the answer with vote up.

推荐答案

您可以传递 maxAge 到期 in options作为中的第3个参数cookie.save function

You can pass maxAge or expires in options as 3rd parameter in cookie.save function

语法:

reactCookie.save(name, val, [opt])

示例:

// maxAge Example
reactCookie.save("token", "token-value", {
   maxAge: 3600 // Will expire after 1hr (value is in number of sec.)
});

// Expires Example
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);

reactCookie.save("token", "token-value", {
   expires: tomorrow // Will expire after 24hr from setting (value is in Date object)
});

文档: https://github.com/eXon/react-cookie#reactcookiesetrawcookiecookies

这篇关于React Cookie + ReactJS:如何设置cookie的到期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆