reactjs - react router dom v5中的嵌套路由和未找到路由
问题描述
在尝试在反应路由器 dom v5 中创建嵌套路由时,我发现这个答案解释了如何很好地做到这一点
(请看这里的代码,因为它与上面提到的答案有点不同)
布局.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>
);
}
授权布局
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} />
编辑:
更清楚一点:我不想只是在<Route component={NotFound} />
里面添加AuthLayout
,AppLayout
因为它会渲染其他东西。我真正需要的是展示顶级水平NotFound
。
解决方案
未找到的组件通常是这样工作的:
<Router>
<Switch>
<Route exact path="/auth" component={AuthLayout} />
<Route exact path="/app" component={AppLayout} />
<Route component={NotFound} />
</Switch>
</Router>
但是你不能标记/auth
and/app
因为exact
它们包含嵌套路由。所以,你应该这样做:
<Router>
<Switch>
<Route path="/auth" component={AuthLayout} />
<Route path="/app" component={AppLayout} />
<Route exact path="/404" component={NotFound} />
<Redirect to='/404' />
</Switch>
</Router>
AppLayout
以及带有嵌套路由的组件(例如):
<>
<h1>App Layout</h1>
<Switch>
<Route path="/app/home" exact component={Home} />
<Route path="/app/dashboard" exact component={Dashboard} />
<Redirect to="/404" />
</Switch>
</>
推荐阅读
- apache-spark - 我可以使用 Airflow 启动/停止火花流作业吗
- blockchain - Restrict function access ONLY to one other specific contract in Solidity
- android - WalletConnect 是否支持“币安智能链(BEP20)”钱包?
- python - How get name of Toplevel window of another Toplevel?
- react-native - 尝试在本机反应中仅显示堆栈导航标题时关闭抽屉标题
- c# - 将所有值从列表添加到列表列表
- php - 2 周内未订购的 woocommerce 用户 sql 查询
- snowflake-cloud-data-platform - 检索覆盖视图 SnowFlake
- java - instanceof 中的模式匹配有时无法解析理论上可解析的范围
- javascript - useContext 未定义