我试图从返回useContext(AuthContext)
的useAuth
中解构onLogout
函数,在这样做的时候,我在控制台中得到一个错误:
错误:未捕获类型错误:无法解构“useAuth(...)”的属性“onLogout”,因为它为Null。
App.js代码段:
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;
};
1条答案
按热度按时间mu0hgdu01#
你不能在
App
中使用useAuth()
,因为它不是AuthProvider
的子级。要做到这一点,请将AuthProvider
调用移动到index
文件中,以获得如下内容:另外,在另一个组件中定义一个组件是不正确的。将
ProtectedRoute
移动到App
之外: