[英]React Router only recognises index route
我有两条路线, /
和/about
,我已经测试了几个。 所有路由仅呈现主页组件/
。
当我尝试不存在的路由时,它会识别出正常并显示警告Warning: No route matches path "/example". Make sure you have <Route path="/example"> somewhere in your routes
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,但在答案中没有找到任何救赎。
任何人都可以解释可能存在的问题吗?
使用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>
);
}
});
既然你已经嵌套About
下Home
需要渲染<RouteHandler />
您内组件Home
组件,以便做出反应路由器能够显示您的路线的组件。
import {RouteHandler} from 'react-router';
var Home = React.createClass({
render() {
return (<div> this is the main component
<RouteHandler />
</div>);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.