复习
上一张我们知道了react-router的基本使用,了解了switch、browserRouter、HashRouter等组件,还知道了this.props的参数,一般就是组件传递的数据和路径相关的对象,例如location、match、history,请牢牢记住这些属性,因为他们在以后很重要
嵌套路由怎么用?
这里我是用一个例子详细解释一哈,
import React, {Component} from 'react'
import {Switch, Route, Redirect} from 'react-router-dom'
import MyNavLink from '../app/MyNavLink'
import News from './news/News'
import Messages from './message/Message'
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
const {path} = this.props.match;
return (
<React.Fragment>
<div>Home组件内容</div>
<div>
<ul className="nav nav-tabs">
<li>
<MyNavLink to={`${path}/news`} style={{marginRight:50,textDecoration:'none'}}>news</MyNavLink>
</li>
<li>
<MyNavLink to={`${path}/messages`} style={{textDecoration:'none'}}>messages</MyNavLink>
</li>
</ul>
</div>
{/*在路由里面有两种方式向组件传值,如一下,props是当前的props,里面包含了history、location、match等
子组件接收还是使用this.props(有状态组件);如若不传props,子组件的props就只有extra
*/}
{/*
这里嵌套路由有两种书写方式:
第一种:父级组件的路由/当前的路由,例如父级的路由是/home,那么news的路由就是/home/news
第二种:当父级路由无参数,使用this.props.match.path/当前路由
当父级路径含有参数是使用this.props.location.pathname?search/当前路由
什么时候用第一种,什么时候用第二种呢?
第一种的使用情况我建议在父级路由层级不超过2层是使用,超过两层则使用第二种,使用第二种时注意父级路由有无参数
*/}
<Switch>
<Route path={`${path}/news`} component={props => <News {...props} extra={'someVariable'} />}/>
<Route path={`${path}/messages`} render={props => <Messages {...props} extra={'someVariable'} />}/>
<Redirect to={`${path}/news`}/>
</Switch>
</React.Fragment>
);
}
}
下一章进入redux。多谢支持