我在控制臺中收到以下錯誤,帶有空白 localhost 螢屏(終端中沒有錯誤):
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$1 (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$1 (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
任何幫助都會很棒!謝謝!
uj5u.com熱心網友回復:
問題很簡單
const user=JSON.parse(localStorage.getItem("user"))
您正在決議它兩次。getItem使用dataType='json', 所以資料已經是json格式。您可以直接將其存盤在variable.
const user= localStorage.getItem("user")
uj5u.com熱心網友回復:
let u = localStorage.getItem("user");
let user=null;
if(typeof u === 'object'){
user = JSON.parse(u);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/448557.html
