react的路由对比vue的路由,感觉vue的路由很方便,集中式管理,react的路由也可以像vue一样实现路由集中式管理
npm 仓库:https://www.npmjs.com/package/react-router-config
文件结构如下:
pages
--home
--one.js
--two.js
--home.js
--child.js
--router.js
--users
--users.js
--router.js
home文件夹下的router.js代码如下,默认显示Home组件,One是一级路由,child是二级路由:
import Home from './home' import One from './one' import Child from './child' import Two from './two' const homeRouter = [ { path: '/', exact: true, component: Home }, { path: '/one', component: One, routes: [ { path: '/one/child', component: Child, exact: true, }, ] }, { path: '/two', component: Two } ] export default homeRouter
如果有二级路由,需要在一级路由的js文件中添加renderRoutes,例如child是one的二级路由,需要在one.js中写入:
import React, { Component } from 'react'; import { renderRoutes } from 'react-router-config' class One extends Component { constructor(props) { super(props); this.state = {} } render() { return ( <div> <p>One</p> <h2> {renderRoutes(this.props.route.routes)}</h2> </div> ); } } export default One;
最关键的app.js代码如下:
import React, { Component } from 'react'; import { BrowserRouter as Router, Link } from 'react-router-dom' import { renderRoutes } from 'react-router-config' import './App.css'; import homeRouter from './pages/home/router'; import userRouter from './pages/users/router' // 合并路由 function NotFound() { return <h2>404</h2> } const notFound = [ { path: '*', component: NotFound } ] const routes = [ ...homeRouter, ...userRouter, ...notFound ] class App extends Component { constructor(props, context) { super(props, context) } render() { return ( <Router> <div> <ul className="nav"> <li><Link to="/">Home</Link></li> <li><Link to="/one">One</Link></li> <li><Link to="/two">Two</Link></li> <li><Link to="/one/child">/one/child</Link></li> <li><Link to="/user">User</Link></li> </ul> {renderRoutes(routes)} {/*<Route path="/" exact component={Home}/> <Route path="/one" component={One}/> <Route path="/two" component={Two} /> <Route path="/user" component={User} />*/} </div> </Router> ) } } export default App;
参考代码:https://github.com/wangweianger/react16-webpack3.8-onepage-base-project
发表评论
侧栏公告
寄语
譬如朝露博客是一个分享前端知识的网站,联系方式11523518。
热评文章
标签列表
热门文章
友情链接