react-router中withRouter的作用

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"
    ]
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值