在重新加载页面重定向到登录页面,尽管url路径保持不变



在React项目中,登录并输入登录页面时工作正常,但在重新加载重定向到登录页面时,url保持不变。请参考下方的代码

这是路由结构

<Routes>
<Route path={home} element={<Navigate to={companyPage} />} />
<Route
path={companyPage}
element={
<ProtectedRoute>
<CompanyPage />
</ProtectedRoute>
}
/>
<Route path="*" element={<RouteNotFound />} />
</Routes>

ProtectedRoute.js(此处路由受保护(

function ProtectedRoute({ children }) {
const { authorized } = useContext(AutorizationContext);
return authorized === true ? children : <Navigate to={RouteConstant.sign} />;
}
ProtectedRoute.propTypes = {
children: PropTypes.element.isRequired
};

什么是最佳的解决方案?任何建议高度赞赏

输入名称和密码作为"测试">

您的状态变量authorized在页面刷新时从true切换为false
一种解决方案是使用localStorageauthorized值存储在临时变量中

useLocalStorage挂钩:

// file path : /src/use-local-storage.js
import { useState } from "react";
function UseLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
if (typeof window === "undefined") {
return initialValue;
}
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.log(error);
return initialValue;
}
});
const setValue = (value) => {
try {
const valueToStore =
value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
if (typeof window !== "undefined") {
window.localStorage.setItem(key, JSON.stringify(valueToStore));
}
} catch (error) {
console.log(error);
}
};
return [storedValue, setValue];
}
export default UseLocalStorage;

在你的App.js中试试这个:

import React, { useEffect, useState } from "react";
import { BrowserRouter } from "react-router-dom";
import AutorizationContext from "./context/auth-context";
import Login from "./pages/login/Login";
import HomePage from "./pages/home/HomePage";
import UseLocalStorage from "./use-local-storage";
export default function App() {
const [authorized, setAuthorized] = useState(false);
const value = { authorized, setAuthorized };
const [savedAuth, setSavedAuth] = UseLocalStorage();
useEffect(() => {
setAuthorized(savedAuth);
}, []);
useEffect(() => {
setSavedAuth(authorized);
}, [authorized, setSavedAuth]);
return (
<BrowserRouter>
<AutorizationContext.Provider value={value}>
{!authorized ? <Login /> : <HomePage />}
</AutorizationContext.Provider>
</BrowserRouter>
);
}

完整的沙箱在这里

相关内容

  • 没有找到相关文章

最新更新