在 React / NextJS 中使用 cookie-react 解析 JSON cookie 时出现奇怪的行为

mic*_*mic 5 javascript reactjs next.js

我有一个名为“_user_attributes”的 cookie。cookie 包含一个 URL 编码的 JSON 数据字符串。例如,

%7B%22user_id%22%20%3A%20%2212345%22%2C%20%22user_givenName%22%20%3A%20%22First%22%20%7D
Run Code Online (Sandbox Code Playgroud)

解码为

{"user_id" : "12345", "user_givenName" : "First" }
Run Code Online (Sandbox Code Playgroud)

基本上,我想将解码后的 cookie 变成一个对象。所以我一直在做以下事情:

var _user_attributes = cookies.get('_user_attributes')
const user_attributes = JSON.parse(_user_attributes)
Run Code Online (Sandbox Code Playgroud)

这有效。但奇怪的是,它仅在我第一次加载页面时有效。如果我刷新页面,我会收到“ SyntaxError: Unexpected token u in JSON at position 0 ”。

我完全不明白为什么会这样。如果有人有任何建议,我将不胜感激。我的页面的完整代码如下。

%7B%22user_id%22%20%3A%20%2212345%22%2C%20%22user_givenName%22%20%3A%20%22First%22%20%7D
Run Code Online (Sandbox Code Playgroud)

Arp*_*ara 1

您在存储在 cookie 中时对 JSON 进行编码,但在读回 cookie 时,cookie 值将直接输入JSON.parse而不进行解码。由于 JSON 解析器无法解析编码值,因此会抛出错误。

这是用于工作cookie检索的codesandbox - https://codesandbox.io/s/silly-shtern-2i4dc?file=/src/App.js

import React, { Component } from "react";
import { withCookies } from "react-cookie";

class Test extends Component {
  constructor(props) {
    super(props);
    const { cookies } = props;
    var _user_attributes = cookies.get("_user_attributes");
    if (_user_attributes) {
      _user_attributes = decodeURI(_user_attributes);
      const user_attributes = JSON.parse(_user_attributes);
      console.log(user_attributes);
      this.state = {
        name: user_attributes.user_givenName
      };
    }
    //if the cookie doesn't exist. added just for testing
    else {
      let temp = { user_id: "12345", user_givenName: "First" };
      temp = encodeURI(JSON.stringify(temp));
      cookies.set("_user_attributes", temp, { path: "/" });
    }
  }
  render() {
    return <p>{this.state?.name || "No Cookie yet"}</p>;
  }
}

export default withCookies(Test);
Run Code Online (Sandbox Code Playgroud)

但我不确定您如何能够在不解码的情况下在首次加载时访问 cookie。

在对页面的任何负载进行解码和解析后,我能够一致地读取 cookie。但如果没有解码,我总是会出错。