react-router中withRouter的作用
withRouter是react-router的一个高阶组件,可获取history
render时会把match, location和history传入props
react中经过路由渲染的组件才拥有路由参数,使用this.props.history.push('/a')跳转到对应路由的页面
使用withRouter可以将路由参数传入this.props中
代码举例:
import React,{Component} from 'react'
import {withRouter} from 'react-router-dom' // 引入react-router-dom/react-router中的withRouter
class App extends Component{
console.log(this.props); // {match: {…}, location: {…}, history: {…}, 等}
render(){return (<div className='app'></div>)
}
}
export default withRouter(App); // 这里通过WithRouter将路由参数传入props中
还有一种实现方法就是在要注入属性的组件上使用'@withRouter'
代码举例:
import React, { Component } from 'react';
import { withRouter } from 'react-router';
@withRouter
export default class Header extends Component {
static displayName = 'Header';
static propTypes = {};
static defaultProps = {};
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div className="header"></div>
);
}
}
使用@这种写法的话,需要babel-plugin-transform-decorators-legacy包
执行:npm install babel-plugin-transform-decorators-legacy --save-dev
还需要在packag文件中的babel中配置,具体实现方式可以查看react @装饰器相关文档
{
"plugins":[
"transform-decorators-legacy"
]
}