React-Router 4 捕获所有路由

问题描述 投票:0回答:5
reactjs react-router-v4
5个回答
18
投票

尝试这个实现

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>
        );
    }

16
投票

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

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

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

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

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


2
投票

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

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


0
投票

这是一个重定向所有其他路线的单行(放置在所有其他路线之后):

<Route path="/*" loader={() => redirect('/')} />

-2
投票

试试这个:

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

在这里,我捕获所有不存在的路由并将它们推送到 404 组件:

<Route path="/*" render={() => (  <PagesError404 /> )} />

记住

  • path
    =
    '/youreRoute'
    但也 =
    {['/']}
    归因于
  • exact
    = 完全匹配
© www.soinside.com 2019 - 2024. All rights reserved.