react router 4.0以上的路由应用
在4.0以下的react router中,嵌套的路由可以放在一个router标签中,形式如下,嵌套的路由也直接放在一起。
但是在4.0以后,嵌套的路由与之前的就完全不同了,需要单独放置在嵌套的根component中去处理路由,否则会一直有warning:
You should not use <Route component> and <Route children> in the same route
正确形式如下
//
上面将嵌套的路由注释掉
const Users = ({ match }) => ()Topics
上面在需要嵌套路由的component中添加新的路由
一个完整的嵌套路由的例子如下
说明及注意事项
- 以下代码采用ES6格式
- react-router-dom版本为4.1.1
- 请注意使用诸如HashRouter之类的history,否则一直会有warning,不能渲染
import React, { Component } from 'react';import ReactDOM from 'react-dom';// import { Router, Route, Link, Switch } from 'react-router';import { HashRouter, Route, Link, Switch} from 'react-router-dom';class App extends Component { render() { return (); }}const About = () => (App
{this.props.children}
- Home
- About
- Inbox
)const Home = () => (About
)const Message = ({ match }) => (Home
)const Inbox = ({ match }) => (new messages
{match.params.id}
) ReactDOM.render( (Topics
), document.getElementById('root'));