React-Router:没有找到路由?

时间:2015-08-20 21:49:01

标签: react-router

请考虑以下事项:

var AppRoutes = [
    <Route handler={App} someProp="defaultProp">
        <Route path="/" handler={Page} />
    </Route>,

    <Route  handler={App} someProp="defaultProp">
        <Route path="/" handler={Header} >
            <Route path="/withheader" handler={Page} />
        </Route>
    </Route>,

    <Route handler={App} someProp="defaultProp">
        <Route path=":area" handler={Area} />
        <Route path=":area/:city" handler={Area} />
        <Route path=":area/:city/:locale" handler={Area} />
        <Route path=":area/:city/:locale/:type" handler={Area} />
    </Route>
];

我有一个App Template,一个HeaderTemplate和一个具有相同处理程序的参数化路由集(在App模板中)。我希望能够在找不到东西时提供404路线。例如,/ CA / SanFrancisco应该由Area找到并处理,而/ SanFranciscoz应该是404.

这是我如何快速测试路线。

['', '/', '/withheader', '/SanFranciscoz', '/ca', '/CA', '/CA/SanFrancisco', '/CA/SanFrancisco/LowerHaight', '/CA/SanFrancisco/LowerHaight/condo'].forEach(function(path){
    Router.run(AppRoutes, path, function(Handler, state){
        var output = React.renderToString(<Handler/>);
        console.log(output, '\n');
    });
});

问题是/ SanFranciscoz总是由Area页面处理,但我希望它为404.另外,如果我将NotFoundRoute添加到第一个路由配置,所有Area页面404。

<Route handler={App} someProp="defaultProp">
    <Route path="/" handler={Page} />
    <NotFoundRoute handler={NotFound} />
</Route>,

我做错了什么?

这里有一个可以下载和试验的要点。

https://gist.github.com/adjavaherian/aa48e78279acddc25315

6 个答案:

答案 0 :(得分:167)

Dejakob的回答是正确的,在反应路由器1.0.0中删除了DefaultRoute和NotFoundRoute。我想强调的是,当前层次结构级别中星号的默认路由必须是最后才能工作。否则它将匹配树中显示的所有路径。

对于react-1,2和3

如果您想显示404并且保留路径(与NotFoundRoute功能相同)

<Route path='*' exact={true} component={My404Component} />

如果您想显示404页面,但更改网址(与DefaultRoute功能相同)

<Route path='/404' component={My404Component} />
<Redirect from='*' to='/404' />

多个级别的示例:

<Route path='/' component={Layout} />
    <IndexRoute component={MyComponent} />
    <Route path='/users' component={MyComponent}>
        <Route path='user/:id' component={MyComponent} />
        <Route path='*' component={UsersNotFound} />
    </Route>
    <Route path='/settings' component={MyComponent} />
    <Route path='*' exact={true} component={GenericNotFound} />
</Route>

对于react-router 4

保持路径

<Switch>
    <Route exact path="/" component={MyComponent} />
    <Route component={GenericNotFound} />
</Switch>

重定向到另一条路线(更改网址)

<Switch>
    <Route path="/users" component={MyComponent} />
    <Redirect to="/404" />
</Switch>

答案 1 :(得分:24)

在较新版本的react-router中,您希望wrap the routes in a Switch只呈现第一个匹配的组件。否则你会看到渲染了多个组件。

例如:

import React from 'react';
import ReactDOM from 'react-dom';
import {
  BrowserRouter as Router,
  Route,
  browserHistory,
  Switch
} from 'react-router-dom';

import App from './app/App';
import Welcome from './app/Welcome';
import NotFound from './app/NotFound';

const Root = () => (
  <Router history={browserHistory}>
    <Switch>
      <Route exact path="/" component={App}/>
      <Route path="/welcome" component={Welcome}/>
      <Route path="*" component={NotFound}/>
    </Switch>
  </Router>
);

ReactDOM.render(
  <Root/>,
  document.getElementById('root')
);

答案 2 :(得分:12)

使用新版本的React Router(现在使用2.0.1),您可以使用星号作为路径来路由所有“其他路径”。

所以它看起来像这样:

<Route route="/" component={App}>
    <Route path=":area" component={Area}>
        <Route path=":city" component={City} />
        <Route path=":more-stuff" component={MoreStuff} />    
    </Route>
    <Route path="*" component={NotFoundRoute} />
</Route>

答案 3 :(得分:4)

根据documentation,找到路径 ,即使资源不是。

  

注意:这不适用于未找到资源的情况。路由器找不到匹配的路径和导致资源未找到的有效URL之间存在差异。 url courses / 123是一个有效的url并导致匹配的路由,因此它被发现&#34;就路由而言。然后,如果我们获取一些数据并发现课程123不存在,我们不希望转换到新路线。就像在服务器上一样,您继续提供并提供不同的UI(并使用不同的状态代码)。你不应该尝试过渡到NotFoundRoute。

因此,您始终可以在Router.run()之前的React.render()中添加一行来检查资源是否有效。只需将prop传递给组件或使用自定义组件覆盖Handler组件即可显示NotFound视图。

答案 4 :(得分:2)

我只是快速浏览一下你的例子,但如果我理解它是正确的方法,你试图将404路由添加到动态段。我几天前遇到了同样的问题,找到了#458#1103,最后在渲染功能中进行了手工检查:

if (!place) return <NotFound />;
希望有所帮助!

答案 5 :(得分:2)

此答案适用于react-router-4。 您可以将所有路由包装在Switch块中,该块的功能类似于switch-case表达式,并使用第一个匹配的路由呈现组件。例如)

<Switch>
      <Route path="/" component={home}/>
      <Route path="/home" component={home}/>
      <Route component={GenericNotFound}/> {/* The Default not found component */}
</Switch>

何时使用exact

无确切内容:

<Route path='/home'
       component = {Home} />

{/* This will also work for cases like https://<domain>/home/anyvalue. */}

准确:

<Route exact path='/home'
       component = {Home} />

{/* 
     This will NOT work for cases like https://<domain>/home/anyvalue. 
     Only for https://<url>/home and https://<domain>/home/
*/}

现在,如果您接受路由参数,并且结果不正确,则可以在目标组件本身中进行处理。例如)

<Route exact path='/user/:email'
       render = { (props) => <ProfilePage {...props} user={this.state.user} />} />

现在在ProfilePage.js中

if(this.props.match.params.email != desiredValue)
{
   <Redirect to="/notFound" component = {GenericNotFound}/>
   //Or you can show some other component here itself.
}

有关更多详细信息,您可以阅读以下代码:

App.js

ProfilePage.js