【发布时间】:2020-10-10 17:14:26
【问题描述】:
在尝试在 react router dom v5 中创建嵌套路由时,我发现 this answer 解释了如何很好地做到这一点
(请看这里的代码,因为它与上面提到的答案有点不同)
Layouts.js
const NotFound = () => <h1>Not Found</h1>;
function Layouts() {
return (
<Switch>
<Route path="/auth" component={AuthLayout} />
<Route path="/app" component={AppLayout} />
<Route path="/" component={NotFound} />
</Switch>
);
}
AuthLayout
const Signup = () => <p>Login</p>;
const Login = () => <p>Sign up</p>;
function AuthLayout() {
return (
<div>
<h1>Auth Layout</h1>
<Route path="/auth/signup" exact component={Signup} />
<Route path="/auth/login" exact component={Login} />
{/* Commenting this because I want to go to NotFound component */}
{/* <Redirect from="/auth" to="/auth/login" exact /> */}
</div>
);
}
应用布局
const Home = () => <p>Home</p>;
const Dashboard = () => <p>Dashboard</p>;
function AppLayout() {
return (
<div>
<h1>App Layout</h1>
<Route path="/app/home" exact component={Home} />
<Route path="/app/dashboard" exact component={Dashboard} />
{/* Commenting this because I want to go to NotFound component */}
{/* Redirect from="/app" to="/app/home" exact /> */}
</div>
);
}
但是这有一个问题,如果你使用/app/somethingnotfound 去一个路由它不会去<Route path="/" component={NotFound} />,它会“留在里面”AppLayout 并且不渲染任何路由。
在这种情况下如何让/app/somethingnotfound 转到<Route path="/" component={NotFound} />?
编辑:
更清楚一点:我不想在AuthLayout 和AppLayout 中添加<Route component={NotFound} />,因为它会渲染其他内容。我真正需要的是展示顶级NotFound。
【问题讨论】:
标签: reactjs react-router react-router-dom react-router-v5