【发布时间】:2023-01-12 23:49:25
【问题描述】:
我正在尝试从返回useContext(AuthContext)的useAuth解构onLogout函数,而在执行此操作时,我在控制台中收到错误消息。
错误:
未捕获的 TypeError:无法解构“useAuth(...)”的属性“onLogout”,因为它为空。
App.js 代码 SN-P:
import React, { createContext, useContext } from "react"; import { Navigate, Route, Routes, useNavigate } from "react-router-dom"; import { useDispatch } from "react-redux"; import { logout, userLogin, userRegister } from "./features/cv"; import { cookieCutter } from "./utils/cookie"; const AuthContext = createContext(null); const AuthProvider = ({ children }) => { const token = cookieCutter("token"); const dispatch = useDispatch(); const navigate = useNavigate(); const handleLogin = (data) => { dispatch(userLogin(data)); navigate("/table"); }; const handleRegister = (data) => { dispatch(userRegister(data)); navigate("/table"); }; const handleLogout = () => { dispatch(logout()); navigate("/login"); }; const value = { token, onLogin: handleLogin, onRegister: handleRegister, onLogout: handleLogout, }; return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>; }; const useAuth = () => { return useContext(AuthContext); }; function App() { const ProtectedRoute = ({ children }) => { const { token } = useAuth(); if (!token) { return <Navigate to="/login" replace />; } return children; }; const userString = JSON.parse(cookieCutter("user") ?? "{}"); const { onLogout } = useAuth(); return ( <AuthProvider> <div> <Routes> <Route path="/" element={ <ProtectedRoute> <Create /> </ProtectedRoute> } /> <Route path="/table" element={ <ProtectedRoute> <Table /> </ProtectedRoute> } /> <Route path="/preview" element={ <ProtectedRoute> <Preview /> </ProtectedRoute> } /> <Route path="/login" element={<Login />} /> <Route path="/register" element={<Register />} /> </Routes> </div> </AuthProvider> )但是,当我在
ProtectedRoute函数中执行相同的操作以获取令牌时,它可以正常工作,但不知道为什么。App.js
ProtectedRoute功能:const ProtectedRoute = ({ children }) => { const { token } = useAuth(); if (!token) { return <Navigate to="/login" replace />; } return children; };
【问题讨论】:
-
你能告诉我们
AuthProvider在哪里使用,并帮助我们把它变成minimal, reproducible example 吗? -
我贴了一个答案;检查一下,请告诉我!
标签: reactjs authentication react-context