【发布时间】:2020-07-23 13:18:44
【问题描述】:
如何使用 React-Router 在 React 中添加 404 - Not Found 页面?
这是我的尝试:
// routes.tsx
export const routes = [
{
path: '/students',
render: (props: any) => <List {...props} title={`Students`} />,
},
{
path: '/teachers',
render: (props: any) => <List {...props} title={`Teachers`} />,
},
]
// App.tsx
import { routes } from './routes'
function App() {
const routeComponents = routes.map(({ path, render }, key) => (
<Route exact path={path} render={render} key={key} />
))
return (
<ThemeProvider theme={theme}>
<CSSReset />
<Suspense fallback={<Loader />}>
<Router>
<Switch>
<Route exact path="/" component={Signin} />
<Route path="/signin" component={Signin} />
<Layout>{routeComponents}</Layout>
{/* <Route component={NotFound} /> */}
<Route path="*" component={NotFound} />
</Switch>
</Router>
</Suspense>
</ThemeProvider>
)
}
export default App
但是当我转到“http://localhost:3000/nothing”时,我看不到我的自定义“404 - 未找到”页面,而是看到<Layout /> 组件。
我做错了什么?
堆栈:TypeScript、React@v16.13.1、react-router-dom@v5.1.2
【问题讨论】:
-
Layout不是Switch的有效子代,只有Route和Redirect是。删除Layout将允许 switch 匹配 404 路由。 reacttraining.com/react-router/web/api/Switch -
谢谢@DrewReese。无论如何,有没有一种方法可以在多个页面(
'/students'、'/teachers')中应用<Layout />而无需添加每个页面? -
将其移到
Switch之外,但仍在Router内应该为您工作。你有它在路线中间的原因吗? -
不,没有特别的原因,我只是不想在几个子组件中添加
<Layout />。但我想我现在就这么做。谢谢@DrewReese
标签: javascript reactjs typescript react-router