1、为了确保所有页面都可以用到路由,直接把<Router>写在根文件下(src/index.js)
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
);
2、react-router 4 默认路由的匹配方式是包容性的,Switch 组件可以使路由变成排他性路由
<Fragment>
//组件式导航
<NavLink to="/" exact activeClassName="active">首页</NavLink>
<NavLink to="/comp2/comp3" activeClassName="active">服务</NavLink>
<NavLink to="/comp4" activeClassName="active">组件3</NavLink>
//NavLink有activeClassName属性,Link没有这个属性
<Switch>
<Route path='/' exact component={Comp1} />
<Route path='/comp2' component={Comp2} />
<Route path='/comp4' component={Comp4} />
<Route component={Page404} />
</Switch>
</Fragment>
3、正常Route的component组件能自动带有3个属性
<Route exact path="/Home" component={Home}/> //exact精准匹配
var Home = ({history,location,match}) => <div>{location.pathname}</div>
//常用:match下面有params,location下有hash、pathname、search、state,history下有push、replace
4、与路由相关的高阶组件 : withRouter
withRouter可以包装任何自定义组件,将react-router 的 history、location、match 三个对象传入。无需一级级传递react-router 的属性,当需要用的router 属性的时候,将组件包一层withRouter,就可以拿到需要的路由信息。
import {withRouter} from 'react-router-dom' ;
var Test = withRouter(({history,location,match})=>{
return <div>{location.pathname}</div>
})
5、路由传值
1>
<Route path=' /user/:id ' component={User}></Route>
|
2>
<Route path=' /user ' component={User}></Route>
<NavLink to={{ pathname:'/comp4', query : { id: 3333 }}}>组件</NavLink> history.push({ pathname : '/comp4' ,query : { id: 3333} }) //编程式导航
User组件里接收值:props.location.query.id |
3>
<Route path=' /user ' component={User}></Route> this.props.history.push( '/user',{id:2222} )
User组件里接收值:props.location.state.id
<NavLink to={{ pathname:'/comp4',state:{ id: 8888 }}}>组件</NavLink> history.push({ pathname:'/comp4',state:{id : 8888 } }) |