【问题标题】:SyntaxError: Unexpected token u in JSON at position 0 at JSON.parseSyntaxError:JSON.parse 中位置 0 处的 JSON 中的意外标记 u
【发布时间】:2021-02-28 06:22:29
【问题描述】:

这里是 Youtube 教程的初学者!我在尝试创建 WhatsApp 克隆程序时收到错误 SyntaxError: Unexpected token u in JSON at JSON.parse () 的位置 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 小时的谷歌搜索无济于事。

【问题讨论】:

  • localStorage.getItem(prefixedKey) 返回什么?看起来它不是有效的 JSON。
  • @Arun Kumar Mohan 我猜它返回 'whatsapp-clone-' (这是前缀)和密钥,但我不确定关键部分应该做什么,也许它是随机的生成的 ID?
  • 如果你在浏览器控制台运行localStorage.getItem('whatsapp-clone-id'),你可以看到里面存储了什么。
  • @Arun Kumar Mohan 当我在调试器中运行它时,它会打开一个带有地址 localhost8080 的 chrome 选项卡,并告诉我它无法访问该站点,我在其中的选项卡中尝试了 React dev tools chrome 扩展'正在运行整个事情,但这甚至没有做任何事情。另外,我将如何运行短代码 sn-p?我对这一切都不熟悉
  • 您可以将console.log(localStorage.getItem('whatsapp-clone-id')) 添加到您的代码中,也可以直接在浏览器控制台中运行。

标签: javascript json reactjs error-handling


【解决方案1】:

由于您在没有第二个参数的情况下调用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 代码运行时,'undefined' 设置在whatsapp-clone-id 键中,因为JSON.stringify(undefined)undefined。错误消息说它无法在运行 JSON.parse(jsonValue) 时解析 JSON,因为第一个字符(位置 0)是 u,它不是有效的 JSON(第一个字符必须是 {)。

修复很简单。仅将值设置为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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多