React-Router 4 捕获所有路由 [英] React-Router 4 catch all route

查看:103
本文介绍了React-Router 4 捕获所有路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 React 路由定义如下:

<代码>...<路由组件={Header}/><路由精确路径="/" component={Landing}/><Route path="/about" component={About}/><Route path="/contact" component={Contact}/><路由组件={Footer}/>...

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

解决方案

试试这个实现

const AppRouter = (props) =>{返回 (<浏览器路由器><div><标题/><开关><路由组件={Header}/><路由精确路径="/" component={Landing}/><Route path="/about" component={About}/><Route path="/contact" component={Contact}/><路由组件={Footer}/><路由组件={NotFoundPage}/></开关>

</BrowserRouter>);}

My React routes are defined as follows:

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

I want to define a catch all route that catches anything that does not match the Landing, About or Contact routes, and instead redirects to a 404 Not found page. How can I do it with React Router 4?

解决方案

Try this implementation

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

这篇关于React-Router 4 捕获所有路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆