我有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);
});
./组件/主
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,但在答案中找不到任何救赎。
任何人都可以了解可能出现的问题吗?
答案 0 :(得分:6)
使用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>
);
}
});
答案 1 :(得分:3)
由于您已在About
下嵌套Home
,因此您需要在<RouteHandler />
组件中呈现Home
组件,以便React Router能够显示你的路线组件。
import {RouteHandler} from 'react-router';
var Home = React.createClass({
render() {
return (<div> this is the main component
<RouteHandler />
</div>);
}
});