使用react 高阶组件withRouter
withRouter 是一个高阶组件,把 match,location,history 三个对象注入到组件的 props 中。这是一个非常实用的函数
react中经过路由渲染的组件才拥有路由参数,使用this.props.history.push(’/a’)跳转到对应路由的页面
一般都是使用withRouter函数调用
import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
class ApiServ extends Component {
render() {
return (
<div>
API
</div>
)
}
}
export default withRouter(ApiServ)
react中有一种装饰器@的方法
create-react-app默认不支持装饰器的,需要做以下配置。
打开 package.json ,可以看到eject。运行 npm run eject 可以让由create-react-app创建的项目的配置项暴露出来(运行之前要保证本地没有待提交git的代码)
"scripts": {
"eject": "react-scripts eject"
}
完成之后本地会多一个config的文件夹
安装babel插件
babel >= 7.x
npm install --save-dev @babel/plugin-proposal-decorators
babel@6.x
npm install --save-dev babel-plugin-transform-decorators-legacy
修改package.json文件的babel配置项
Babel >= 7.x
"babel": {
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }]
],
"presets": [
"react-app"
]
}
babel@6.x
"babel": {
"plugins": [
"transform-decorators-legacy"
],
"presets": [
"react-app"
]
}
下面就可以使用装饰圈@了
import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
@withRouter
class ApiServ extends Component {
render() {
return (
<div>
API
</div>
)
}
}
export default ApiServ