Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) at App.js:18:1 in console

Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) at App.js:18:1 in console

我在本地主机屏幕空白的控制台中收到以下错误(终端中没有错误):

VM256:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at App.js:18:1
    at invokePassiveEffectCreate (react-dom.development.js:23487:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at flushPassiveEffectsImpl (react-dom.development.js:23574:1)
    at unstable_runWithPriority (scheduler.development.js:468:1)
    at runWithPriority (react-dom.development.js:11276:1)
    at flushPassiveEffects (react-dom.development.js:23447:1)

这是 App.js 文件

import React,{useEffect,createContext,useReducer,useContext} from 'react';
import NavBar from './components/Navbar';
import "./App.css"
import {BrowserRouter,Route,Routes,useNavigate} from 'react-router-dom';
import Home from './components/screens/Home';
import Signup from './components/screens/Signup';
import Signin from './components/screens/Signin';
import Profile from './components/screens/Profile';
import CreatePost from './components/screens/CreatePost';
import { reducer,initialState } from './reducers/userReducer';

const UserContext=createContext()

const Routing=()=>{
  const Navigate=useNavigate()
  const {state,dispatch}=useContext(UserContext)
  useEffect(()=>{
    const user=JSON.parse(localStorage.getItem("user"))
    if(user){
      dispatch({type:"USER",payload:user})
      Navigate.push('/')
    }
    else{
      Navigate.push('/signin')
    }
  },[])

  return(
      <Routes>
      <Route exact path="/" element={<Home />}/>
        <Route path="/signin" element={<Signin />}/>
        <Route path="/signup" element={<Signup />}/>
        <Route path="/profile" element={<Profile />}/>
        <Route path="/createpost" element={<CreatePost />}/>
    </Routes>
  )
}


function App() {
  const [state,dispatch]=useReducer(reducer,initialState)
  return (
    <UserContext.Provider value ={{state,dispatch}}>
    <BrowserRouter>
    <NavBar/>
    <Routing/>
    </BrowserRouter>
    </UserContext.Provider>
  );
}

export default App;

我曾尝试使用 JSON.parse(JSON.stringify(...)),但后来我收到 Navigate.push 不是函数的错误。 此外,当我执行控制台日志以查看对象类型时,它应该是一个字符串,但在这里它是未定义的。

现在当它导航到登录时,控制台中出现另一个错误:

Uncaught TypeError: Cannot destructure property 'state' of '(0 , react__WEBPACK_IMPORTED_MODULE_0__.useContext)(...)' as it is undefined.
    at Signin (Signin.js:7:1)
    at renderWithHooks (react-dom.development.js:14985:1)
    at mountIndeterminateComponent (react-dom.development.js:17811:1)
    at beginWork (react-dom.development.js:19049:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at beginWork (react-dom.development.js:23964:1)
    at performUnitOfWork (react-dom.development.js:22776:1)
    at workLoopSync (react-dom.development.js:22707:1)

这是登录文件:

import React,{useState,useContext} from 'react';
import {Link, useNavigate} from 'react-router-dom';
import UserContext from '../../App'
import M from 'materialize-css'

const Signin=()=>{
    const {state,dispatch}=useContext(UserContext)
    const navigate = useNavigate()
    const [password,setPassword] = useState("")
    const [email,setEmail] = useState("")
    const PostData=()=>{
        if(!/^(([^<>()\[\]\.,;:\s@"]+(\.[^<>()\[\]\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email)){
            M.toast({html: "invalid email", classes:"#c62828 red darken-3"})
            return
        }
        fetch("/signin",{
            method:"post",
            headers:{
                "Content-type":"application/json"
            },
            body: JSON.stringify({
                password,
                email
            })
        }).then(res=>res.json())
        .then(data=>{
            console.log(data)
            if(data.error){
                M.toast({html: data.error, classes:"#c62828 red darken-3"})
            }
            else{
                localStorage.setItem("jwt",data.token)
                localStorage.setItem("user",JSON.stringify(data.user))
                dispatch({type:"USER",payload:data.user})
                M.toast({html:"successfully signed-in",classes:"#43a047 green darken-1"})
                navigate('/')
            }
        }).catch(err=>{
            console.log(err)
        })
    }
    return(
        <div className="mycard">
            <div className="card auth-card input-field">
                <h2>PASSit</h2>
                <input
                type="text"
                placeholder="email"
                value={email}
                onChange={(e)=>setEmail(e.target.value)}
                />
                <input
                type="text"
                placeholder="password"
                value={password}
                onChange={(e)=>setPassword(e.target.value)}
                />
                <button className="btn waves-effect waves-light #0288d1 light-blue darken-2"
                onClick={()=>PostData()}
                >Login
  </button>
  <h5>
      <Link to="/signup">Don't have an account ?</Link>
  </h5>
        </div>
        </div>
    )
}

export default Signin

任何帮助都会很棒! 谢谢!

let u = localStorage.getItem("user");
let user=null;
if(typeof u === 'object'){
   user = JSON.parse(u);
}

问题很简单

const user=JSON.parse(localStorage.getItem("user"))

您正在解析它两次。 getItem 使用 dataType='json',所以数据已经是 json 格式。您可以直接将其存储在variable.

const user= localStorage.getItem("user")