总结一下遇到的react-router-dom应用

(1)根据路由切换浏览器的title属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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);
switch(location.pathname){
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);

(2)withRouter()的常见应用:

作用:

(1)withRouter可以用来给组件注入router相关的一些参数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'// A simple component that shows the pathname of the current location

class ShowTheLocation extends React.Component {

static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}

render() {
const { match, location, history } = this.props

return (
<div>You are now at {location.pathname}</div> );
}
}

(2)其次withRouter是专门用来处理数据更新问题的。

在使用一些redux的的connect()或者mobx的inject()的组件中,如果依赖于路由的更新要重新渲染,会出现路由更新了但是组件没有重新渲染的情况。这是因为redux和mobx的这些连接方法会修改组件的shouldComponentUpdate

使用withRouter解决更新问题的时候,一定要保证withRouter在最外层,比如withRouter(connect(Component))

(3)NavLink用来做导航样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// header.js
<li className="tab">
<NavLink exact to="/" activeClassName="active">
<span className="menu-text">首页</span>
<iclassName="iconfontic-navigation-discover menu-icon">&#xe61f;<i>
</NavLink>
</li>
<li className="tab">
<NavLink to="/download" activeClassName="active">
<span className="menu-text">下载App</span>
<i className="iconfont ic-navigation-download menu-icon">&#xe608;</i>
</NavLink>
</li>

// home.js
<NavLink to="/detail" className="title" >{itemInfo.title}</NavLink>

//App.js
import { BrowserRouter as Router, Route } from 'react-router-dom';
<Router >
<Header />
<Route exact path="/" component={Home}></Route>
<Route path="/detail" target="_blank" render={() => (<div>details~</div>)}></Route>
<Route path="/download" render={() => (<div></div>)}></Route>
</Router>

点击首页和下载App会切换组件,并且点击的链接activeClassName会被激活,给定激活class样式。失去激活状态的恢复样式:

1
2
3
4
5
6
li.tab>a.active {
color: #ea6f5a;
}
li.tab>a:not(.active):hover {
background-color: #f5f5f5;
}
-------------要说再见啦感谢大佬的光临~-------------