作用
把不是通过路由切换过来的组件中,将react-router 的 history、location、match 三个对象传入props对象上。
默认情况下必须是经过路由匹配渲染的组件才存在this.props,才拥有路由参数,才能使用编程式导航的写法,执行this.props.history.push(’/detail’)跳转到对应路由的页面。
然而不是所有组件都直接与路由相连(通过路由跳转到此组件)的,当这些组件需要路由参数时,使用withRouter就可以给此组件传入路由参数,此时就可以使用this.props。
使用场景
1.避免更新受阻
因为react-redux的connect高阶组件会为传入的参数组件实现shouldComponentUpdate 这个钩子函数,
导致只有prop发生变化时才触发更新相关的生命周期函数(含render)而很显然,我们的location对象并没有作为prop传入该参数组件
// before
export default connect(mapStateToProps)(Something)
// after
import { withRouter } from 'react-router-dom'
export default withRouter(connect(mapStateToProps)(Something))
2.在组件中意图使用history来控制路由跳转
import React from "react";
import {withRouter} from "react-router-dom";
class MyComponent extends React.Component {
...
myFunction() {
this.props.history.push("/some/Path");
}
...
}
export default withRouter(MyComponent);
如果我们不使用withRouter来处理(MyComponent),那么我们这里的this.props就取不到history,会报hitstory
is undefined之类的错。
3.antd左侧菜单刷新后保持选中状态
当刷新页面时,默认选中菜单项的设置,因为menu的selectedKeys属性存储key值,即我们使用的path路径,我们知道this.props.location.pathname可以取到path的路径,但是当前Layouts不是路由组件,不能通过this.props.location来取到需要的值,此时我们借助react-router-dom的withRouter
使用:
引入Import{ withRouter } from 'react-router-dom';
export default withRouter(Layouts);
//export的时候用withRouter包装一下
参考链接: