簡體   English   中英

語法錯誤:在 JSON 中的意外令牌 u 在 position 0 在 JSON.parse

[英]SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse

初學者在此處學習有關 YoutTube 的教程:我收到錯誤 SyntaxError。 意外的令牌 u 在 JSON.parse () 的 JSON.parse () 中的 JSON 在 position 0 中,我不知道代碼的第一部分為什么:

import { useEffect, useState } from 'react'

const PREFIX = 'whatsapp-clone-'

export default function useLocalStorage(key, initialValue) {
    const prefixedKey = PREFIX + key

    const [value, setValue] = useState(() => {
        const jsonValue = localStorage.getItem(prefixedKey)

        if (jsonValue != null) return JSON.parse(jsonValue)
        if (typeof initialValue === 'function') {
            return initialValue()
        } else {
            return initialValue
        }
    })

    useEffect(() => {
        localStorage.setItem(prefixedKey, JSON.stringify(value))
    }, [prefixedKey, value])

    return [value, setValue]
}

這是另一個重要的部分:

import React from 'react';
import Login from './Login'
import useLocalStorage from '../hooks/useLocalStorage';

function App() {
  const [id, setId] = useLocalStorage('id')

  return (
    <>
      {id}
      <Login onIdSubmit={setId} />
    </>
  )
}

export default App;

這是我得到的第一個錯誤,我相信這會導致其中的 rest。 錯誤img1

感謝您的幫助,我花了大約 2 個小時谷歌搜索無濟於事。

由於您在沒有第二個參數的情況下調用useLocalStorage('id') ,因此initialValueundefined

if (jsonValue != null) return JSON.parse(jsonValue)
if (typeof initialValue === 'function') {
  return initialValue()
} else {
  return initialValue // this lines gets executed when `jsonValue` is null
}

最初, localStorage不包含whatsapp-clone-idjsonValuenull導致上面的else塊運行,將value設置為undefined initialValueundefined

localStorage.setItem(prefixedKey, JSON.stringify(value))

並且當useEffect代碼運行時,由於JSON.stringify(undefined)undefined ,因此在whatsapp-clone-id鍵中設置了'undefined' The error message says it couldn't parse the JSON on running JSON.parse(jsonValue) since the first character (at position 0) is u which is not valid JSON (The first character has to be { ).

修復很簡單。 如果存在,則僅將值設置為initialValue 否則,將其設置為null{}

const jsonValue = localStorage.getItem(prefixedKey)
if (jsonValue != null) {
  return JSON.parse(jsonValue)
}
if (typeof initialValue === "function") {
  return initialValue()
}
if (initialValue) {
  return initialValue
}

return null

在嘗試新代碼之前,您必須運行localStorage.removeItem('whatsapp-clone-id')

暫無
暫無

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

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