React Router 只识别索引路由

IT技术 javascript reactjs react-router
2021-05-01 14:50:15

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

当我尝试一条不存在的路线时,它会识别出该路线并显示警告 Warning: No route matches path "/example". Make sure you have <Route path="/example"> somewhere in your routes

应用程序.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);
});

./组件/主要

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,但没有找到答案。

任何人都可以阐明可能是什么问题吗?

2个回答

使用 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);

附带说明一下,如果要将未找到的路由与特定视图匹配,请使用以下命令:

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

由于您已经嵌套AboutHome您的<RouteHandler />组件中,因此您需要Home组件中渲染一个组件,以便 React Router 能够显示您的路由组件。

import {RouteHandler} from 'react-router';

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