前言:
本文为个人学习react-router的总结。包括路由基础配置,跳转,权限管理,组件与路由配置的关系,代码分割。欢迎交流指导。
一、路由基础
1.路由配置 & 显示路由组件的view(类比angular的ui-view)
路由配置:路由匹配的规则
render(( <Router history={ hashHistory }> <Route path="/" component={ App }> <Route path="select" component={ Select }></Route> <Route path="found" component={ Found }></Route> <Route path="follow" component={ Follow }></Route> <Route path="my" component={ My }> <Route path=":myname" component={ MyName }></Route> <Route path="mysex" component={ MySex }></Route> </Route> </Route> </Router> ), document.getElementById('root'));
view:放置路由组件的地方(URL匹配了,然后对应的组件应该放到什么地方去),
每一个Route都只是一个组件,子路由就是 this.props.children 里面的组件,Route通过匹配URL决定显示哪一个子路由
class App extends PureComponent { render() { return ( <div> <GlobalNav /> { this.props.children } { /* this.props.children 是被嵌套在App的组件,相当于放子路由的View*/} </div> ) } }
二、默认路由(IndexRoute )
组件<App /> 的匹配路径是 ‘/', 有四个子路由,当前路由只是'/',那么<App />应该显示什么页面呢?
这里给与IndexRoute组件 -- 若希望直接使用4个其中一个则使用IndexRedirect
render(( <Router history={ hashHistory }> <Route path="/" component={ App }> <IndexRoute component={ IndexApp } /> <Route path="select" component={ Select }></Route> <Route path="found" component={ Found }></Route> <Route path="follow" component={ Follow }></Route> <Route path="my" component={ My }> <Route path=":myname"