[英]Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>)
When I used localStorage
for store cart
item, then show me error in console box: Uncaught SyntaxError: Unexpected token u in JSON at position 0
like this, and my output is blank nothing to show,当我将localStorage
用于商店cart
项目时,然后在控制台框中显示错误: Uncaught SyntaxError: Unexpected token u in JSON at position 0
像这样,而我的 Z78E6221F6393D135DZFCE 什么都没有显示
I have tried like this:我试过这样:
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));
};
In the cartAction.js
file I have used localStorage.setItem("cartItems", JSON.stringify(getState().cart.cartItems));
在cartAction.js
文件中,我使用了localStorage.setItem("cartItems", JSON.stringify(getState().cart.cartItems));
line.线。
then store.js
file:然后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;
If I'm not use this logic如果我不使用这个逻辑
cart: {
cartItems: localStorage.getItem("cartItems")
? JSON.parse(localStorage.getItem("cartItems"))
: [],
},
Inside initialState
then does not show me any error, but when I used this then show me error.然后在initialState
内部不会显示任何错误,但是当我使用它时会显示错误。
Any suggestion please.请有任何建议。
Probably you saved undefined
into the storage because getState().cart.cartItems
was undefined at some point.可能您将undefined
保存到存储中,因为getState().cart.cartItems
在某些时候未定义。
This is a one-way route as you discovered, because JSON.stringify(undefined)
will actually return undefined
(not as string) but saving it into localStorage
casts it to a string, ending up as "undefined"
.正如您所发现的,这是一条单向路线,因为JSON.stringify(undefined)
实际上会返回undefined
(而不是字符串),但将其保存到localStorage
会将其转换为字符串,以"undefined"
结尾。 Now "undefined"
(unlike ""
or undefined
) is truthy, so your check doesn't detect it as empty, but then JSON.parse("undefined")
will fail because that's not valid JSON, hence the "u"
at the start failing already.现在"undefined"
(与""
或“ undefined
”不同)是真实的,因此您的检查不会将其检测为空,但随后 JSON.parse( "u"
JSON.parse("undefined")
将失败,因为这不是有效的 JSON,因此在已经开始失败了。
It would be best to not try to store undefined
at all (check for it first).最好不要尝试存储undefined
(首先检查它)。 Likely the state doesn't have the cart items yet at the time at which you try to read them, it sounds like an asynchronous timing issue ( dispatch
is asynchronous, the state won't change synchronously immedately after you called it). state 在您尝试读取它们时可能还没有购物车项目,这听起来像是一个异步计时问题( dispatch
是异步的,state 在您调用它后不会立即同步更改)。 As jmargolisvt mentioned in the comments, try reading it in a reducer instead.正如评论中提到的 jmargolisvt ,请尝试在减速器中阅读它。
(Then make sure to delete the bad value from your local storage manually so your code can run again.) (然后确保手动从本地存储中删除错误值,以便您的代码可以再次运行。)
But to avoid the situation where the app is just broken for the user and won't load until they delete their local site data (if they even think of that) - regardless of what caused it - I usually wrap JSON.parse
with data from localStorage
in a try
/ catch
where I just consider exceptions as empty value, so at least the app will still work and just have lost the data.但是为了避免应用程序刚刚为用户损坏并且在他们删除本地站点数据(如果他们甚至想到这一点)之前不会加载的情况 - 不管是什么原因造成的 - 我通常用JSON.parse
包装来自在try
/ catch
中的localStorage
我只是将异常视为空值,因此至少该应用程序仍然可以工作并且只是丢失了数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.