【问题标题】:Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>)未捕获的语法错误:JSON.parse (<anonymous>) 位置 0 处的 JSON 中的意外标记 u
【发布时间】:2021-03-17 12:48:46
【问题描述】:

当我使用 localStorage 存储 cart 项目时,然后在控制台框中显示错误:Uncaught SyntaxError: Unexpected token u in JSON at position 0 就像这样,我的输出是空白的,没有什么可显示的,

我试过这样:

import axios from "axios";
import { CART_ADD_ITEM } from "../constants/cartConstants";

export const addToCart = (productId, qty) => async (dispatch, getState) => {
  const { data } = await axios.get(`/api/products/${productId}`);
  dispatch({
    type: CART_ADD_ITEM,
    payload: {
      name: data.name,
      image: data.image,
      price: data.price,
      countInStock: data.countInStock,
      product: data._id,
      qty,
    },
  });
  localStorage.setItem("cartItems", JSON.stringify(getState().cart.cartItems));
};

cartAction.js 文件中,我使用了localStorage.setItem("cartItems", JSON.stringify(getState().cart.cartItems)); 行。

然后store.js文件:

import { applyMiddleware, combineReducers, compose, createStore } from "redux";
import thunk from "redux-thunk";
import { cartReducer } from "./reducer/cartReducer";
import {
  productDetailsReducer,
  productListReducer,
} from "./reducer/productReducer";

const initialState = {
  cart: {
    cartItems: localStorage.getItem("cartItems")
      ? JSON.parse(localStorage.getItem("cartItems"))
      : [],
  },
};

const reducer = combineReducers({
  productList: productListReducer,
  productDetails: productDetailsReducer,
  cart: cartReducer,
});

const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const store = createStore(
  reducer,
  initialState,
  composeEnhancer(applyMiddleware(thunk))
);

export default store;

如果我不使用这个逻辑

cart: {
    cartItems: localStorage.getItem("cartItems")
      ? JSON.parse(localStorage.getItem("cartItems"))
      : [],
  },

initialState 内部则不会显示任何错误,但是当我使用它时会显示错误。

请给点建议。

【问题讨论】:

  • 你要做的第一件事就是检查你传递给JSON.parse()的字符串。
  • 即“未定义”中的“u”。您错误地假设调度将同步设置状态。如果你 setItem 在减速器而不是动作中,你将能够正确设置 localStorage。
  • 您是否查看了引用相同错误的any of the 288 other questions

标签: javascript json reactjs redux


【解决方案1】:

您可能将 undefined 保存到存储中,因为 getState().cart.cartItems 在某些时候未定义。

正如您所发现的,这是一条单向路线,因为 JSON.stringify(undefined) 实际上会返回 undefined(不是字符串),但将其保存到 localStorage 会将其转换为字符串,以 "undefined" 结尾。现在"undefined"(与""undefined 不同)真实的,所以您的检查不会将其检测为空,但随后JSON.parse("undefined") 将失败,因为这不是有效的 JSON,因此"u" 一开始就失败了。

最好不要尝试存储undefined(首先检查它)。在您尝试读取它们时,状态可能还没有购物车项目,这听起来像是一个异步计时问题(dispatch 是异步的,在您调用它后状态不会立即同步更改)。正如 cmets 中提到的 jmargolisvt,请尝试在 reducer 中读取它。

(然后确保手动从本地存储中删除错误值,以便您的代码可以再次运行。)

但是为了避免应用程序刚刚为用户损坏并且在他们删除本地站点数据(如果他们甚至想到这一点)之前不会加载的情况 - 不管是什么原因造成的 - 我通常会包装 JSON.parse将来自localStorage 的数据放在try/catch 中,我只是将异常视为空值,因此至少该应用程序仍然可以工作并且只是丢失了数据。

【讨论】:

  • 谢谢!,当我清除我的 localStorage 后,显示另一个错误,如下所示:Unhandled Rejection (TypeError): Cannot read property 'find' of undefined
  • 您显示的代码中没有对find 的调用。如果这是一个新错误,最好打开一个新问题,其中包含专门针对该错误的调试详细信息,包括堆栈和包含导致错误的调用的代码。
  • 我正在尝试逐步解决您的答案,如果解决了请告诉您,谢谢。
猜你喜欢
  • 1970-01-01
  • 2022-06-13
  • 1970-01-01
  • 2017-06-27
  • 2022-06-17
  • 2018-03-29
  • 2020-04-12
  • 1970-01-01
  • 2022-01-26
相关资源
最近更新 更多