У меня проблема с React Router (v.5). Я написал ProtectedRoute и вспомогательный компонент AdmindRoute.
export function ProtectedRoute(props: ProtectedRouteProps)
{
console.log({...props});
const location = useLocation();
if (props.path !== location.pathname)
{
return null;
}
const getToken = (): string | undefined =>
{
const storageService: StorageService = new StorageService();
return storageService.read<string>(StorageKeys.JWT);
}
const isAuthenticated = (): boolean =>
{
const token: string | undefined = getToken();
if (token === undefined || token === null)
{
return false;
}
return true;
}
if (!isAuthenticated())
{
return <Redirect to={{ pathname: props.authenticationPath }}/>;
}
else
{
return <Route exact {...props}/>;
}
}
export function AdmindRoute(props: ProtectedRouteProps)
{
const location = useLocation();
if (props.path !== location.pathname)
{
return null;
}
const getToken = (): string | undefined =>
{
const storageService: StorageService = new StorageService();
return storageService.read<string>(StorageKeys.JWT);
}
const isAdmin = () : boolean =>
{
const token: string | undefined = getToken();
if (token === undefined || token === null)
{
return false;
}
const userInfoJSON = JSON.parse(JSON.stringify(getDecodedAccessToken(token)));
const roles: any[] = userInfoJSON.auth;
if (roles.toEnum().Any(x => x.authority === "ROLE_ADMIN"))
{
return true;
}
const storageService: StorageService = new StorageService();
storageService.remove(StorageKeys.JWT)
return false;
}
const getDecodedAccessToken = (token: string) =>
{
try
{
return jwt_decode(token);
}
catch (error)
{
return null;
}
}
if (!isAdmin())
{
return <Redirect to={{ pathname: props.authenticationPath }}/>;
}
else
{
return <Route {...props}/>;
}
Мои маршруты:
export const AppRoutes = () =>
<React.Fragment>
<Route exact path={ Urls.home } component={ HomePage } />
<ProtectedRoute {...defaultProtectedRouteProps} exact path={ Urls.products } component={ ProductsPage } />
<ProtectedRoute {...defaultProtectedRouteProps} exact path={ Urls.details } component={ DetailsPage } />
<AdmindRoute {...defaultProtectedRouteProps} exact path={ Urls.addProduct } component={ AddProductPage } />
</React.Fragment>
Мои URL-адреса:
export enum Routes
{
//public
Home = "",
//prptected
Products = "products",
Details = "details",
//admin
AddProduct = "admin/product/add"
}
export module Urls
{
//public
export const home = `/${Routes.Home}`;
//protected
export const products = `/${Routes.Products}`;
export const details = `/${Routes.Details}`;
//admin
export const addProduct = `/${Routes.AddProduct}`;
}
Моя проблема заключается в переходе из AddProduct страницы (http://localhost: 7777 / admin / product / add ) к странице продуктов (должно быть: http://localhost: 7777 / products ) маршрутизатора только в последнем сегменте браузера url: http://localhost: 7777 / admin / product / products .
Не могу найти, что я сделал не так.
thnx