考虑路由器:
<Router>
<Fragment>
<Navbar />
{/* <Landing /> */}
<Route exact path="/" component={Landing} />
<section className="containerSpecial">
<Alert />
<Switch>
<Route exact path="/register" component={Register} />
<Route exact path="/forgot-my-password" component={ForgotMyPassword}/>{" "}
<Route exact path="/reset-password" component={ResetPassword} />
<Route exact path="/login" component={Login} />
<PrivateRoute exact path="/dashboard" component={Dashboard} />{" "}
... More PrivateRoutes
// Another route that forwards to "NotFound" Component
</Switch>
</section>
</Fragment>
</Router>
当用户点击诸如 http://localhost:3000/dashboard
之类的 url 或来自
上面列出的,正在转发到相应的组件。
但是,当用户点击 http://localhost:3000/ddlksajldsajk 或 http://localhost:3000/dashboard1 时
没有任何内容被渲染。
如何将未列出的 URL 转发到 NotFound
组件?
最佳答案
只需添加 <Route component={NoMatch} />
:
<Router>
<Fragment>
<Navbar />
{/* <Landing /> */}
<Route exact path="/" component={Landing} />
<section className="containerSpecial">
<Alert />
<Switch>
<Route exact path="/register" component={Register} />
<Route exact path="/forgot-my-password" component={ForgotMyPassword}/>{" "}
<Route exact path="/reset-password" component={ResetPassword} />
<Route exact path="/login" component={Login} />
<PrivateRoute exact path="/dashboard" component={Dashboard} />{" "}
... More PrivateRoutes
// Another route that forwards to "NotFound" Component
<Route component={NotFound} />
</Switch>
</section>
</Fragment>
</Router>
关于javascript - React - 如何将未在路由器中列出的路由请求转发到 NotFound (404) 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60572649/