React Router仅识别索引路由

Kie*_*iee 2 javascript reactjs react-router

我有2条路线,/并且/about我已经测试了几条路线.所有路由只渲染主组件/.

当我尝试一条不存在的路线时,它会识别出这种情况并显示警告 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);
});
Run Code Online (Sandbox Code Playgroud)

./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
};
Run Code Online (Sandbox Code Playgroud)

我试过添加一条明确的路径即将无济于事. <Route name="about" path="/about" handler={About} />

我偶然发现了这个stackoverflow Q,但在答案中没有找到任何救赎.

任何人都可以解释可能存在的问题吗?

小智 5

使用ES6和最新的react-router看起来像这样:

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);
Run Code Online (Sandbox Code Playgroud)

在旁注中,如果要将未显示的路由与特定视图匹配,请使用以下命令:

<Route component={NotFound} path="*"></Route>
Run Code Online (Sandbox Code Playgroud)

请注意路径设置为*

还要编写自己的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>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)