简体   繁体   English

语法错误:在 JSON 中的意外令牌 u 在 position 0 在 JSON.parse

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

total beginner following a tutorial on YoutTube here: I get the error SyntaxError.初学者在此处学习有关 YoutTube 的教程:我收到错误 SyntaxError。 Unexpected token u in JSON at position 0 at JSON.parse () while trying to create a WhatsApp clone program and I have no idea why: Here's the first part of the code:意外的令牌 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]
}

And here's the other essential part:这是另一个重要的部分:

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;

Here's the first error I get, which I believe leads to the rest of them.这是我得到的第一个错误,我相信这会导致其中的 rest。 错误img1

Thanks for any help, I spent like 2 hours googling to no avail.感谢您的帮助,我花了大约 2 个小时谷歌搜索无济于事。

Since you're calling useLocalStorage('id') without a second argument, initialValue is undefined .由于您在没有第二个参数的情况下调用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
}

Initially, localStorage does not contain whatsapp-clone-idjsonValue is null which causes the else block above to run, setting value to undefined .最初, localStorage不包含whatsapp-clone-idjsonValuenull导致上面的else块运行,将value设置为undefined ( initialValue is undefined ) initialValueundefined

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

And when the useEffect code runs, 'undefined' is set in the whatsapp-clone-id key since JSON.stringify(undefined) is undefined .并且当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 { ). 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 { ).

The fix is simple.修复很简单。 Only set the value to initialValue if it's present.如果存在,则仅将值设置为initialValue Otherwise, set it to null or {} .否则,将其设置为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

You'll have to run localStorage.removeItem('whatsapp-clone-id') before trying the new code.在尝试新代码之前,您必须运行localStorage.removeItem('whatsapp-clone-id')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未捕获到的SyntaxError:JSON中的意外令牌u在JSON.parse的位置0 - Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse SyntaxError:JSON中的意外令牌u在JSON.parse( <anonymous> ) - SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) Uncaught SyntaxError: JSON.parse (<anonymous> ) 在 Response.Body.json</anonymous> - Uncaught SyntaxError: Unexpected token U in JSON at position 0 at JSON.parse (<anonymous>) at Response.Body.json 未捕获的语法错误:JSON 中的意外令牌 u 在 JSON.parse 的 position 0 处(<anonymous> )</anonymous> - Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) 未捕获的语法错误:JSON 中的意外令牌 u 在 JSON.parse 的 position 0 处(<anonymous> ) at./src/context/AuthContext.js</anonymous> - Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) at ./src/context/AuthContext.js VM299:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous> ) - VM299:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) 使用JSON.parse时,&#39;未捕获的SyntaxError:意外的标记u&#39; - 'Uncaught SyntaxError: Unexpected token u' when using JSON.parse JSON.parse导致“未捕获的SyntaxError:意外的令牌u” - JSON.parse causes “Uncaught SyntaxError: Unexpected token u” 未捕获的SyntaxError:JSON.parse中位置0的JSON中的意外标记a( <anonymous> ) - Uncaught SyntaxError: Unexpected token a in JSON at position 0 at JSON.parse (<anonymous>) JSON.parse() 导致错误:`SyntaxError: Unexpected token in JSON at position 0` - JSON.parse() causes error: `SyntaxError: Unexpected token in JSON at position 0`
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM