我有这个代码来呈现 Jmeter 板时,它检测到用户名是“管理员”。但我得到一个错误,说用户名没有值或空的地方,事实上有一个值后,它登录到本地存储。以下是我的代码i
mport { createContext, useReducer, useEffect } from "react";
export const AuthContext = createContext()
export const authReducer = (state, action) => {
switch (action.type) {
case 'LOGIN':
return { user: action.payload }
case 'LOGOUT':
return { user: null }
default:
return state
}
}
export const AuthContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(authReducer, {
user: null
})
useEffect(() => {
const user = JSON.parse(localStorage.getItem('user'))
if(user){
dispatch({type: 'LOGIN', payload: user})
}
},[])
{console.log('AuthContext state:', state)}
return (
<AuthContext.Provider value={{ ...state, dispatch }}>
{children}
</AuthContext.Provider>
)
}
import { useState } from "react";
import { useAuthContext } from "./useAuthContext";
export const useLogin = () => {
const [error, setError] = useState(null)
const [isLoading, setIsLoading] = useState(null)
const { dispatch } = useAuthContext()
const login = async (username, password) => {
setIsLoading(true)
setError(null)
const response = await fetch('/credentials/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password })
})
const json = await response.json()
if(!response.ok){
setIsLoading(false)
setError(json.error)
}
else{
localStorage.setItem('user', JSON.stringify(json))
//update AuthContext
dispatch({type: 'LOGIN', payload: json})
setIsLoading(false)
}
}
return { login, isLoading, error }
}
如果它获得的用户是admin,我将其设置为this,然后呈现 Jmeter 板。
const Home = () => {
const { user } = useAuthContext()
return (
<div>
<Container>
<Routes>
<Route
path="/"
element={user.username=="admin" ? <Dashboard title="Dashboard" user="User" /> : <Navigate to="/login" />}
/>
但它会导致系统崩溃,并在控制台中显示“user.username为空
1条答案
按热度按时间t1qtbnec1#
我不确定开始调试这段代码的上下文,但它看起来像对象
user
,它没有定义。尝试记录此用户状态,并确保填充了用户对象数据。我看到您使用了一个三元if来重定向用户,使用可选链接来避免空/未定义对象的错误
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
在这里放置上下文代码,并检查所有这些内容的 Package 器