2015-09-06 100 views
2

我有2條路由,/和​​,我已經測試了幾個。所有路由只呈現/的主頁組件。React路由器只識別索引路由

當我嘗試的路徑不存在它承認罰款,並顯示警告 Warning: No route matches path "/example". Make sure you have <Route path="/example"> somewhere in your routes

App.js

import React from 'react'; 
import Router from 'react-router'; 
import { DefaultRoute, Link, Route, RouteHandler } from 'react-router'; 
import {Home, About} from './components/Main'; 

let routes = (
    <Route name="home" path="/" handler={Home} > 
     <Route name="about" handler={About} /> 
    </Route> 
); 

Router.run(routes, function (Handler) { 
    React.render(<Handler/>, document.body); 
}); 

./components/Main

import React from 'react'; 

var Home = React.createClass({ 
    render() { 
     return <div> this is the main component </div> 
    } 
}); 

var About = React.createClass({ 
    render(){ 
     return <div>This is the about</div> 
    } 
}); 

export default { 
    Home,About 
}; 

我試過添加一個顯式路徑幾乎無濟於事。 <Route name="about" path="/about" handler={About} />

我已經偶然發現了這個stackoverflow Q,但在答案中沒有發現任何救贖。

任何人都可以闡明什麼可能是問題?

回答

3

既然你Home下築巢About你需要爲了你Home組件中渲染<RouteHandler />組件的陣營路由器能夠顯示您的路線的組件。

import {RouteHandler} from 'react-router'; 

var Home = React.createClass({ 
    render() { 
     return (<div> this is the main component 
      <RouteHandler /> 
     </div>); 
    } 
}); 
6

使用ES6和最新的反應,路由器應該是這樣的:

import React from 'react'; 
import { 
    Router, 
    Route, 
    IndexRoute, 
} 
from 'react-router'; 

const routes = (
    <Router> 
    <Route component={Home} path="/"> 
     <IndexRoute component={About}/> 
    </Route> 
    </Router> 
); 

const Home = React.createClass({ 
    render() { 
    return (
     <div> this is the main component 
     {this.props.children} 
     </div> 
    ); 
    } 
}); 

//Remember to have your about component either imported or 
//defined somewhere 

React.render(routes, document.body); 

在一個側面說明,如果你想unfound路由匹配到一個特定的視圖,使用:

<Route component={NotFound} path="*"></Route> 

注意路徑設置爲*

也寫你自己的NotFound組件。

礦看起來像這樣:

const NotFound = React.createClass({ 
    render(){ 
    let _location = window.location.href; 
    return(
     <div className="notfound-card"> 
     <div className="content"> 
      <a className="header">404 Invalid URL</a > 
     </div> 
     <hr></hr> 
     <div className="description"> 
      <p> 
       You have reached: 
      </p> 
      <p className="location"> 
      {_location} 
      </p> 
     </div> 
     </div> 
    ); 
    } 
});