【发布时间】:2021-12-28 22:23:51
【问题描述】:
我有一个简单的路由系统,其中有一个页面作为容器 (Home Page),在其中我有两个部分 (NewPage 和 StoredPage)。
我将所有路线设置都放在一个地方,即 App.tsx 中。我这样做是为了保持集中并更好地控制(我不知道我是否做错了)。
发生的问题是,在更改部分时,它正在闪烁,由于某种原因它正在重新加载页面。
注意:我使用react-router-guards
APP.TSX
import HomePage from 'pages/HomePage';
import StoredPage from 'pages/StoredPage';
import { memo, useMemo } from 'react';
import { BrowserRouter, Switch, Redirect } from 'react-router-dom';
import { GuardedRoute, GuardProvider, Next } from 'react-router-guards';
import { GuardFunctionRouteProps, GuardToRoute } from 'react-router-guards/dist/types';
export const Main = memo(() => {
const RequireLoginGuard = (to: GuardToRoute, from: GuardFunctionRouteProps | null, next: Next) => next();
return (
<ErrorBoundary instance={instance}>
<BrowserRouter>
<GuardProvider guards={[RequireLoginGuard]} loading={() => <div>Loading Global</div>}>
<Switch>
<GuardedRoute exact path='/new' loading={() => <div>Loading New Page</div>} component={HomePage} />
<GuardedRoute exact path='/stored' loading={() => <div>Loading Stored Page</div>} component={HomePage} />
<GuardedRoute path='*' component={() => <Redirect to='/new' />} />
</Switch>
</GuardProvider>
</BrowserRouter>
</ErrorBoundary>
);
});
HOMEPAGE.TSX
import NewPage from 'pages/NewPage';
import StoredPage from 'pages/StoredPage';
import { useMemo } from 'react';
import { Route, Router, Switch } from 'react-router-dom';
import SectionTitle from 'xpi-black-ui/Common/SectionTitle';
import Navigation from '../../components/Navigation';
import MainContainer, { SectionContainer } from './styles';
const HomePage = () => {
const navigationItems = useMemo(
() => [
{
key: 'new',
title: 'New Quotation',
link: '/new',
component: () => <NewPage />,
},
{
key: 'stored',
title: 'New Quotation 2',
link: '/stored',
component: () => <StoredPage />,
},
],
[]
);
return (
<MainContainer>
<SectionContainer>Aaaaaaaaaaaaaaa</SectionContainer>
<SectionContainer isSecondary>
<SectionTitle>
<Navigation />
<div>C</div>
</SectionTitle>
<Switch>
{navigationItems.map(({ key, link, component: PageComponent }) => (
<Route key={key} path={link} component={PageComponent} exact />
))}
</Switch>
</SectionContainer>
</MainContainer>
);
};
NAVIGATION.TSX
import { useCallback } from 'react';
import { useLocation } from 'react-router-dom';
import NavLink, { Container } from './styles';
const Navigation = () => {
const { pathname } = useLocation();
const isActive = useCallback((linkPathSelected) => pathname === linkPathSelected, [pathname]);
const links = [
{ key: 'new', to: '/new', title: 'Criar Cotação' },
{ key: 'stored', to: '/stored', title: 'Cotações Armazenadas' },
];
return (
<Container>
{links.map(({ key, to, title }) => (
<NavLink exact key={key} to={to} $isActive={isActive(to)}>
{title}
</NavLink>
))}
</Container>
);
};
【问题讨论】: