在React单页面应用中,UI组件的展示和切换需要由路由控制,每个路由对应不同的URL及路由信息。
react-router v2和 v3版本
在react-router v2和 v3版本中,路由需要在开始渲染前就定义好完整的结构,所有路由同事初始化才能生效,比如:
<Router history={browserHistory}>
<Route path='/' component={App}>
<IndexRoute component={Home} />
<Route path='first' component={First} />
<Route path='second' component={Second} />
</Route>
</Router>
比较简单明了,但是路由层层嵌套,必须在渲染应用前统一声明,在大型项目中路由太多,路由配置文件会有很多,可能会这样使用:
<Router history={browserHistory} routes={routeConfig}>
</Router>
routeConfig中做如下配置:
const routeConfig = [
{
path: '/',
component: App,
indexRoute: {component: Homepage},
getChildRoutes: getChildRoutes
},
{
path: '/login',
component: Login,
}]
getChildRoutes 的方法如下:例如:将workbench-route.js引入
const getChildRoutes = (location, cb) => {
require.ensure([], require => {
cb(null, [
require('./workbench-route').default
])
})
}
workbench-route.js如下:
const workbench = (location, cb) => {
require.ensure([], require => {
cb(null, require('../components/workbench/WorkbenchIndex.js').default)
}, 'workbench')
};
const workbenchRoute = {
path: 'workbench',
getComponent: workbench,
childRoutes: [
{path: 'datareport',
getComponent: datareport,
childRoutes:[
{path:'reportlist',getComponent:reportlist},
{path:'columntypereport',getComponent:columntypereport},
{path:'customizeform',getComponent:customizeform}
]
}]
}
export default workbenchRoute ;
如果某路由下有子路由 则该路由需要如下处理:以workbench为例
class WorkbenchIndex extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
react-router v4.x
相比之前版本,减少了配置化的痕迹,更凸显了组件化的组织方式,而且在渲染组件时才实现该部分路由。
export default class APP extends React.Component {
render(){
return (
<div>
<HashRouter>
<Switch>
<Route path="/" exact component={MainPage} ></Route>
<Route path="/manage" component={Index} ></Route>
</Switch>
</HashRouter>
</div>)
}
}
ReactDOM.render(<APP/> , document.getElementById('root'));
路由可以在渲染组件中声明,不需依赖于其他路由,不需要集中配置;
假设manage路由下有二级路由则在上述manage路由对应的Index组件配置即可:
export default class Index extends React.Component{
render(){
return (
<div>
<Route path={`${this.props.match.url}`} exact component={FirstRoute}></Route>
<Route path={`${this.props.match.url}/manageSecond`} component={SecondRoute}></Route>
</div>)
}
}
当路由跳转到manage时,会加载FirstRoute组件,当路由跳转到manage/manageSecond时会加载SecondRoute组件。需加exact,若不加跳转manage/manageSecond时,路由会匹配manage导致加载FirstRoute组件而不是SecondRoute组件。跳转路由的方法如下:
this.props.history.push('/manage')
this.props.history.push('/manage/manageSecond')
react-router v4.x 刚接触,只懂皮毛,有什么不妥之处望见谅。
通过路由传值:
使用 render 可以给 SecondRoutePage组件传值,SecondRoutePage组件可通过this.props.name得到值