标签:info col style 使用 执行 cat img document oca
import React,{Component} from ‘react‘
import {Switch,Route,NavLink,Redirect,withRouter} from ‘react-router-dom‘ //引入withRouter
import One from ‘./One‘
import NotFound from ‘./NotFound‘
class App extends Component{
//此时才能获取this.props,包含(history, match, location)三个对象
console.log(this.props); //输出{match: {…}, location: {…}, history: {…}, 等}
render(){return (<div className=‘app‘>
<NavLink to=‘/one/users‘>用户列表</NavLink>
<NavLink to=‘/one/companies‘>公司列表</NavLink>
<Switch>
<Route path=‘/one/:type?‘ component={One} />
<Redirect from=‘/‘ to=‘/one‘ exact />
<Route component={NotFound} />
</Switch>
</div>)
}
}
export default withRouter(App); //这里要执行一下WithRouter
二:介绍一个简单应用
可以根据路由切换浏览器的title属性,对props.history进行监听,切换路由的时候获取当前的路由路径,同时可以根据不同的路由设置不同的浏览器title标题。
仍然是App.js组件:
import React,{Component} from ‘react‘
import {Switch,Route,NavLink,Redirect,withRouter} from ‘react-router-dom‘
import One from ‘./One‘
import NotFound from ‘./NotFound‘
class App extends Component{
constructor(props){
super(props);
props.history.listen((location)=>{ //在这里监听location对象
console.log(location.pathname); //切换路由的时候输出"/one/users"和"/one/companies"
switch(location.pathname){ //根据路径不同切换不同的浏览器title
case ‘/one/users‘ : document.title = ‘用户列表‘; break;
case ‘/one/companies‘ : document.title = ‘公司列表‘; break;
default : break;
}
})
}
render(){
return (<div className=‘app‘>
<NavLink to=‘/one/users‘>用户列表</NavLink>
<NavLink to=‘/one/companies‘>公司列表</NavLink>
<Switch>
<Route path=‘/one/:type?‘ component={One} />
<Redirect from=‘/‘ to=‘/one‘ exact />
<Route component={NotFound} />
</Switch>
</div>)
}
}
export default withRouter(App);
页面效果:

当点击“用户列表”,浏览器标题会显示:
当点击“公司列表”,浏览器标题会显示:
三:当然还有众多用途,如果你使用了编程式导航的写法:
this.props.history.push(‘/detail‘) 去跳转页面,但是报 this.props.history 错误 undefined,请在此组件中使用 withRouter 将 history 传入到 props上。
标签:info col style 使用 执行 cat img document oca
原文地址:https://www.cnblogs.com/luowenshuai/p/9526341.html