不知何故,我想到了一個問題,即如果該人單擊鏈接,則應將其重定向到未授權的登錄頁面,如果已授權,則應重定向到該頁面。這聽起來很簡單,但問題是我想讓用戶重定向到一個應該被授權的頁面,用戶授權并重定向到他點擊的同一頁面。
現在,我有一個看起來像這樣的受保護路由:(我有fromPath下一次重定向的論據,但這對我不起作用。)
const ProtectedRoute = ({
isAllowed,
redirectPath = "/sign-in",
fromPath = null,
children,
}) => {
const dispatch = useDispatch();
if (fromPath) dispatch(setURLPath(fromPath));
if (!isAllowed) {
return <Navigate to={fromPath} replace />;
}
return children ? children : <Outlet />;
};
從App.js側面看它是這樣的:
<Suspense fallback={<Spinner />}>
<GlobalStyle />
<Routes>
<Route
path='/'
element={
<ProtectedRoute
isAllowed={roleLevel > 0}
/>
}
>
<Route path='bookings' element={<BookingsPage />} />
<Route path='single-booking/:id' element={<SingleBookingPage />} />
<Route path='documents' element={<DocumentsPage />} />
<Route path='my-account' element={<MyAccountPage />} />
<Route path='reservation' element={<ReservationPage />} />
</Route>
</Route>
<Route path='*' element={<NotFoundPage />} />
</Routes>
</Suspense>
uj5u.com熱心網友回復:
組件應獲取正在訪問的路由的ProtectedRoute當前location物件,并將其以路由狀態傳遞給登錄路由。
import { useLocation } from 'react-router-dom';
const ProtectedRoute = ({
isAllowed,
redirectPath = "/sign-in",
fromPath = null,
children,
}) => {
const location = useLocation();
const dispatch = useDispatch();
if (fromPath) dispatch(setURLPath(fromPath));
if (!isAllowed) {
return <Navigate to={fromPath} replace state={{ from: location }} />;
}
return children ? children : <Outlet />;
};
然后登錄組件應該訪問傳遞的路由狀態并重定向回正在訪問的原始路由。
const location = useLocation();
const navigate = useNavigate();
...
const login = () => {
...
const { from } = location.state || { from: { pathname: "/" } };
navigate(from, { replace: true });
};
uj5u.com熱心網友回復:
例如,您可以通過傳遞一些引數(next_route)來實作這一點。并在登錄程序中保留它,這樣當他完成時,他可以重新重定向到正確的位置(next_route)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/472692.html
標籤:javascript 反应 反应路由器 jsx 反应路由器dom
