不是通过路由切换过来的组件中,如何在props中获取history

withRouter作用
  • 首先,我们需要知道withRouter作用,把不是通过路由切换过来的组件中,将react-router 的 history、location、match 三个对象传入props对象上。
  • 在下边例子中如果不通过withRouter函数props中没有history对象。
withRouter使用方式:

首先要引入

import { withRouter } from 'react-router-dom';

将不是通过路由切换过来的组件,但是又需要获取history对象组件通过withRouter包裹。

withRouter(组件名)

由于我项目中使用dvajs来调用接口,所以,用connect连接一下,将props中传入dispatch函数。

import React from 'react';
import { withRouter } from 'react-router-dom';
import notification from 'utils/notification';

import { connect } from 'dva';

function ProductionMonitoringDashboard(props) {
  function handleGoHome() {
    const { history } = props;
    history.push('/');
  }
  return (
    <div>
      <div>
        <div>
          <div className={styles['title-block']}>
            <img src={logoLeft} alt="logo-left" className={styles['logo-left']} />
            <span style={{ cursor: 'pointer' }} onClick={handleGoHome}>
              看板标题
            </span>
            {timeComponent}
            <img src={logoRight} alt="logo-right" className={styles['logo-right']} />
          </div>
          <div className={styles['announcement-block']}>
            <div>
              <img alt="announcement" />
              <span>产线动态:欢迎校领导莅临指导</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default connect()(withRouter(ProductionMonitoringDashboard));

到此组件中能够获取到history对象。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值