簡體   English   中英

反應錯誤 - Uncaught SyntaxError: Unexpected token o in JSON at position 1

[英]react error - Uncaught SyntaxError: Unexpected token o in JSON at position 1

我切換了我的后端數據庫,創建了一個新的超級用戶,然后將 yarn start 到 go 到開發環境中進行反應。 現在才得到這個錯誤

VM4135:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse ()

我認為問題在於我正在同時提取 web 令牌和用戶數據。 然后將它們存儲在本地存儲中,但是由於這是新啟動,因此本地存儲中沒有任何內容,它正在尋找不存在的令牌? 我不太確定這是否正確,但我似乎無法克服它。

任何幫助,將不勝感激。

拋出錯誤的個人資料頁面。

const user = JSON.parse(localStorage.getItem("user") || {});
const Profile = () => (
  <div className={s.root}>
    <h1 className="page-title">
      User - <span className="fw-semi-bold">Profile</span>
    </h1>
      ...

令牌和用戶身份驗證操作

// token and user auth
export function receiveToken(payload) {
  return (dispatch) => {
    const user = payload.user;
    const token = payload.token;

    delete user.id;
    localStorage.setItem("token", token);
    localStorage.setItem("user", JSON.stringify(user));
    axios.defaults.headers.common["Authorization"] = `Token ${token}`;
    dispatch(receiveLogin());
  };
}

完全錯誤

VM4135:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at Module../src/pages/profile/Profile.js (Profile.js:8)
    at __webpack_require__ (bootstrap:781)
    at fn (bootstrap:149)
    at Module../src/components/Layout/Layout.js (InputValidation.js:72)
    at __webpack_require__ (bootstrap:781)
    at fn (bootstrap:149)
    at Module../src/components/App.js (useraccounts.js:44)
    at __webpack_require__ (bootstrap:781)
    at fn (bootstrap:149)
    at Module../src/index.js (a6.jpg:1)
    at __webpack_require__ (bootstrap:781)
    at fn (bootstrap:149)
    at Object.1 (theme.scss?2910:45)
    at __webpack_require__ (bootstrap:781)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)
    at main.chunk.js:1

問題似乎出在第一行。 您無法parse有效的 JavaScript Object。 將您的行更改為:

const user = JSON.parse(localStorage.getItem("user")) || {};

這是來自控制台的示例。

安慰

另外,檢查localStorage.getItem("user")的內容。 如果,它將某些東西存儲為[object Object]怎么辦? 因此,當您設置本地存儲項目時,請確保您這樣做:

const user = {some: "obj"};
localStorage.setItem(JSON.stringify(user));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM