简体   繁体   English

如何使用 react-cookie 读取 cookie?

[英]How to read a cookie with react-cookie?

I am building a FullStack App with React and Express.我正在使用 React 和 Express 构建一个 FullStack 应用程序。 I am using react-cookie.我正在使用反应饼干。 After submit a form i set cookies in my browser then i render a new page in my application.提交表单后,我在浏览器中设置了 cookies,然后在我的应用程序中呈现了一个新页面。

 setCookie("jwt", `${data.jwt}`, { path: "/" }); setCookie("user", `${data.name}`, { path: "/" });

Then i want to read a cookie in that component and i do not know how can i do it.然后我想读取该组件中的 cookie,但我不知道该怎么做。 So if someone have any idea how to do it please write below:) Thanks:)因此,如果有人知道如何做,请写在下面:) 谢谢:)

You can use the hook useCookies like this:您可以像这样使用钩子useCookies

import { useCookies } from 'react-cookie';

const [cookies, setCookie, removeCookie] = useCookies(['cookie-name']);

const myCookie = cookies.get('cookie-name')

You could use much simpler way like this (make sure you have installed react-cookie FIRST!)你可以使用像这样更简单的方法(确保你已经安装了 react-cookie FIRST!)

import { useCookies } from 'react-cookie';

const [cookies, setCookie, removeCookie] = useCookies();

// set Cookie
setCookie('access_token','your_token_value_here')

// read cookie with 
console.log(cookies.access_token) 

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

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