一、下载
npm install react-cookies
二、导入
import cookie from 'react-cookies'
三、存值
1、登录成功,将信息保存在cookie中( 存值 )
{ path: ‘/’ } 加上这个就是表示这个cookie 键值对 可以被所有页面访问到。
存值的语法:cookie.save(key, value, { path: '/' })
if (retJsonInfo.code == 200) {
message.success("登录成功");
// 将用户信息保存在cookie中,
this.onLogin(JSON.stringify(data)) //这里的data是后端返回的用户信息(根据自己项目所定)
} else {
message.error(retJsonInfo.msg);
}
onLogin(data) {
// 失效时间 15分钟
let expires = new Date(new Date().getTime() + 15 * 60 * 1000);//15分钟
// 存信息
cookie.save('userInfo', data, { path: '/', expires }) //key值在这里是“userInfo”(自己随便取的)
}
四、取值
取值的语法:cookie.load(key)
componentDidMount () {
let userInfo = cookie.load("userInfo") //这个’userInfo就是刚刚自己取的名字‘
console.log(userInfo,'userInfo')
}
五、删除值
删除值的语法:cookie.remove(key, { path: '/' })
cookie.remove("userInfo")