我正在使用 react-router@latest 和代码拆分创建一个反应应用程序。一切正常,除了当我单击关于链接或仪表板链接时布局组件会重新呈现所有内容。请帮我解决这个问题。我已经阅读了许多博客文章,但没有得到任何适合我的解决方案。
我为该https://github.com/riyasat/ReactRouterTest创建了一个存储库。
这是我的组件
主要部件
const Main = () => {
// const Layout = React.lazy(()=>import('../Core/Layout'));
return (
<div>
<ErrorBoundary>
Router Test
<Switch>
<Route exact path="/">
<Redirect to="en"></Redirect>
</Route>
<Route path="/:lang"
>
<Layout/>
</Route>
</Switch>
</ErrorBoundary>
</div>
);
};
export default Main;
布局组件
import React, { Suspense, useEffect } from "react";
import { Redirect, Route, Switch, useRouteMatch } from "react-router-dom";
const Layout = () => {
const { url, path } = useRouteMatch();
const About =React.lazy(() => import("../Views/About"));
const Dashboard = React.lazy(() => import("../Views/Dashboard"));
useEffect(() => {
console.log("Layout Mounted");
return () => {
console.log("Un Mounted");
};
});
return (
<div>
This is Router
<Switch>
<Route exact path={`${path}`}>
<Redirect to={`${url}/about`} />
</Route>
<Route exact path={`${path}/about`}>
<About/>
</Route>
<Route exact path={`${path}/dashboard`} >
<Dashboard/>
</Route>
</Switch>
</div>
);
};
export default Layout;
关于组件
const About = () => {
return (
<div>
<Link to="dashboard">Dashboard</Link>
</div>
)
}
export default About;
仪表板组件
const Dashboard = () => {
return (
<div>
<NavLink to={`about`}>About</NavLink>
</div>
)
}
export default Dashboard;