React Router 挂载和卸载父组件

React Router mounting and unmounting parent component

我正在使用 react-router@latest 和代码拆分创建一个 React 应用程序。一切正常,除了布局组件会在我单击关于 link 或仪表板 link 时重新呈现所有内容。请帮我解决这个问题。我已经阅读了很多博客文章,但没有找到适合我的解决方案。

我已经为那个 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;

这是因为 useRouteMatch 会导致它所在的组件在 URL 发生变化时重新渲染。如果您删除它并将 urlpath 更改为固定值(即字符串),则布局组件不应在路由更改时重新呈现