React-Router的之前版本支持路由通过path和Route标签直接嵌套,看起来简洁明了,但是4之后的版本不支持了,原因据说是为了践行React的组件化理念,不能让Route标签看起来只是一个标签…。
//示例1、RR4之前的嵌套路由写法
import {
Router,
Route,
IndexRoute,
hashHistory
} from 'react-router';
import App from './views/App.js';
import Login from './views/Login';
class MyMouter extends React.Component {
render(){
return(
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Login}/>
<Route path="login" component={Login}/>
<Route path="userInfo" getComponent={pageFrame}>
<Route path="change" getComponent={userInfoChange}/>
</Route>
</Route>
</Router>
)
}
}
export default MyRouter
既然不能使用Route嵌套,那该怎么办呢?由两种写法:
- 在component组件内部需要嵌套的位置直接嵌套Route标签
如示例1、RR4之前的路由嵌套写法,在component组件中需要使用this.props.children来表示嵌套子组件,而在4中,我们必须直接将Route标签写入到父组件之中,而且路由必须包含根路径,RR4不会帮我们自动拼接location。
//示例2、Route在componnt中的直接嵌套
//root.js
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={hashHistory}>
<div>
<Route path="/" component={App} />
</div>
</ConnectedRouter>
</Provider>,
document.getElementById('root')
)
//App.js
render() {
return (
<div className="App">
<Switch>
<Route path="/login" exact render={(({location}) => (<h1>来玩啊,小帅哥</h1>)) } />
<Route path="/" component={Portal} />
</Switch>
</div>
);
}
//Portal.js
render() {
return (
<Content style={{background : '#FFF', padding : 24, margin : 0, minHeight : 200}}>
<Route path="/" exact render={() => (<h1>弗雷尔卓德必将再次统一!</h1>)} />
<Route path="/products" exact component={Products} />
<Route path="/search" exact component={ProductSearch} />
</Content>
);
}
- 使用Route render渲染作内联嵌套
使用Route component方法进行路由嵌套遵从了组件化要求,但也使Route标签分散在各个层级的组件之中,如果我们仍然喜欢使用4之前的集中配置方法,可以使用Route的render方法进行内联嵌套。此时,component仍可以使用this.props.children进行嵌套渲染。
//示例3、render内联渲染
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={hashHistory}>
<div>
<Route path="/" render={({history,location}) => (
<App history={history} location={location} />
<Switch>
<Route path="/login" exact render={(({location}) => (<h1>来玩啊,小帅哥</h1>)) } />
<Route path="/" render={({history,location,match}) => (
<Portal history={history} location={location} match={location}>
<Route path="/" exact render={() => (<h1>弗雷尔卓德必将再次统一!</h1>)} />
<Route path="/products" exact component={Products} />
<Route path="/search" exact component={ProductSearch} />
</Portal>
)} />
</Switch>
</App>
)} />
</div>
</ConnectedRouter>
</Provider>,
document.getElementById('root')
)