![](/img/trans.png)
[英]Uncaught SyntaxError: Unexpected token u in JSON at position 0 at 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;
感謝您的幫助,我花了大約 2 個小時谷歌搜索無濟於事。
由於您在沒有第二個參數的情況下調用useLocalStorage('id')
,因此initialValue
是undefined
。
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-id
— jsonValue
是null
導致上面的else
塊運行,將value
設置為undefined
。 ( initialValue
值undefined
)
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.