React-Router 4捕获所有路由

Jam*_*mes 2 reactjs react-router-v4

我的React路由定义如下:

...
<Route component={Header} />
<Route exact path="/" component={Landing} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route component={Footer} />
...
Run Code Online (Sandbox Code Playgroud)

我想定义一个“全部捕获”路由,以捕获与着陆,“关于”或“联系”路由不匹配的所有内容,而是重定向到“ 404找不到”页面。我该如何使用React Router 4?

Wer*_*ous 8

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

<Route path="/*" render={() => <SomeComponent /* possible prop injection */ />}/>
Run Code Online (Sandbox Code Playgroud)

我经常使用它,但你也可以使用

<Route render={() => <SomeComponent />} />
Run Code Online (Sandbox Code Playgroud)

我不经常使用这个,因为我更喜欢我的代码中的更多地标,但我从https://tylermcginnis.com/react-router-handling-404-pages/得到了上述内容

  • 奖励:`&lt;SomeComponent /&gt;`可以是`&lt;Redirect /&gt;` (2认同)

Shu*_*ala 5

试试这个实现

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

  • 两件事:a)我认为这将在所有页面中呈现`NotFoundPage';而且,b)我认为您不需要两次&lt;Header /&gt;`,就像代码中那样。 (2认同)
  • 在“Switch”中,只会呈现 1 场比赛。没有“path”的“Route”始终是匹配的。因此,如果没有其他匹配,将呈现“NotFoundPage”。“页眉”和“页脚”都不应该包含在“开关”中(我已对此答案提交了编辑以修复该部分代码) (2认同)