react中的withRouter

高阶组件中的withRouter, 作用是将一个组件包裹进Route里面, 然后react-router的三个对象history, location, match就会被放进这个组件的props属性中.

 1 // withRouter实现原理: 
 2 // 将组件包裹进 Route, 然后返回
 3 // const withRouter = () => {
 4 //     return () => {
 5 //         return <Route component={Nav} />
 6 //     }
 7 // }
 8 
 9 // 这里是简化版
10 const withRouter = ( Component ) => () => <Route component={ Component }/>

上面是实现的原理, react-router-dom 里面是有这个组件的, 直接引入使用就可以了。

 1 import React from 'react'
 2 import './nav.css'
 3 import {
 4     NavLink,
 5     withRouter
 6 } from "react-router-dom"
 7 
 8 class Nav extends React.Component{
 9     handleClick = () => {
10         // Route 的 三个对象将会被放进来, 对象里面的方法可以被调用
11         console.log(this.props);
12     }
13     render() {
14         return (
15             <div className={'nav'}>
16                 <span className={'logo'} onClick={this.handleClick}>掘土社区</span>
17                 <li><NavLink to="/" exact>首页</NavLink></li>
18                 <li><NavLink to="/activities">动态</NavLink></li>
19                 <li><NavLink to="/topic">话题</NavLink></li>
20                 <li><NavLink to="/login">登录</NavLink></li>
21             </div>
22         );
23     }
24 }
25 
26 // 导出的是 withRouter(Nav) 函数执行
27 export default withRouter(Nav)

所以withRouter的作用就是, 如果我们某个东西不是一个Router, 但是我们要依靠它去跳转一个页面, 比如点击页面的logo, 返回首页, 这时候就可以使用withRouter来做.

在这个例子中, 我将span使用withRouter作为一个可点击跳转的Link