React Router 4 - Route to a default component if a broken link has entered

时间:2017-08-05 10:59:51

标签: reactjs redux react-router react-router-v4

I am working on React Router 4. I have some components like home, page1.., and page404. I want to redirect to the page404 if a broken link has entered.

            <Router>
                <AppContainer>
                    <Route exact path={HOME_URL} component={Home}/>
                    <Route path={SEARCH_RESULTS_URL} component={SearchResults}/>
                    <Route path={PAGE_404} component={Page404}/>
                </AppContainer>
            </Router>

Can anyone please suggest a method.

4 个答案:

答案 0 :(得分:2)

The docs seem to indicate that you have to wrap this in a <Switch>:

<Switch>
    <Route exact path={HOME_URL} component={Home}/>
    <Route path={SEARCH_RESULTS_URL} component={SearchResults}/>
    <Route component={PAGE_404}/>
</Switch>

答案 1 :(得分:1)

开关的工作原理如下,你将它放到一个带有渲染组件的路径的末尾,在我的例子中,我刚刚返回了一个段落。因此,如果用户访问的网址不是您定义的网页,则会返回页面

 <Router>
          <Switch>
            <Route exact path='/' component={Home}/>
            <Route exact path='/about' component={About}/>
            <Route path='/about/results' component={Results}/>
            <Route path='/popular' component={Popular}/>
            <Route render={function () {
              return <p> 404 Page </p>
            }} />
          </Switch>
      </Router>

答案 2 :(得分:1)

    const routes = (
     <BrowserRouter>
      <Switch>
        <Route path="/home" component={Home/>
        <Route path="/about" component={About}/>
        <Route path="*" component={NotFound}/>
      </Switch>
    </BrowserRouter>
   );

答案 3 :(得分:0)

如果路线与最后一条路径不匹配,请抓住路线:

<Route component={page404} />