React-Router 4 捕获所有路由

React-Router 4 catch all route

我的React路由定义如下:

...
<Route component={Header} />
<Route exact path="/" component={Landing} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route component={Footer} />
...

我想定义一个 catch all 路由,它捕获任何与 Landing、About 或 Contact 路由不匹配的内容,而是重定向到 404 Not found 页面。我如何使用 React Router 4 做到这一点?

试试这个实现

const AppRouter = (props) => {
        return (
            <BrowserRouter>
                <div>
                    <Header />
                    <Switch>
                        <Route exact path="/" component={Landing} />
                        <Route path="/about" component={About} />
                        <Route path="/contact" component={Contact} />
                        <Route component={NotFoundPage} />
                    </Switch>
                    <Footer />
                </div>
            </BrowserRouter>
        );
    }

不确定这是否适合你,因为我正在使用一些第 3 方 babel 包装器,但我没有声明我所有的路线然后最后放置

<Route path="/*" render={() => <SomeComponent /* possible prop injection */ />}/>

我经常使用这个,但你也可以使用

<Route render={() => <SomeComponent />} />

我用得不多,因为我更喜欢在我的代码中使用更多地标,但我从 https://tylermcginnis.com/react-router-handling-404-pages/

React 有一个名为 switch 的组件来自 'react-router-dom'

因此,通过将路由包装在 Switch 中,React Router 将仅呈现匹配的第一个路由。这意味着所有其他不匹配的路由都将通过指定没有属性的路由来捕获。参见 https://ui.dev/react-router-v4-handling-404-pages/

试试这个: ( < SomeComponent /> / possible prop injection */ )} />

我在这里捕获所有 none 现有路由结束将其推送到 404 组件:

( )} />

记得

  • path = '/youreRoute' 但也 = {['/']} attributed
  • exact = 完全匹配