react 跳转后路由变了页面没刷新

问题

这样的问题貌似原因还挺多的,我的问题是带参数的url不能刷新,router 5.0版本 ,使用withRouter关联组件进行页面跳转
如下所示
在这里插入图片描述
路由代码
在这里插入图片描述

解决方案

在路由组件上最上层元素上加一个key增加路由的识别度,因为普通的跳转是根据path来识别的,但是path带上参数时,路由无法精确识别。不过,在跳转页面的时候,每个地址都会在localtion对象里添加一个key。如下打印

 // 组件挂载
  componentDidMount() {
    console.log(this.props.location);
  }

在这里插入图片描述
我们将这个key绑定在 路由顶层元素上就能精确定位路由了

 render() {
    return (
      {/*就是这个key*/}
      <div key={this.props.location.key}>
          <Switch>
            <Route exact path="/" component={Home} />
            <Route exact path="/products/:id" component={Products} />
            <Route exact path="/about" component={About} />
            <Route exact path="/solution" component={Solution} />
            <Route
              exact
              path="/solutionDetails/:id"
              component={SolutionDetails}
            />
            <Route exact path="/download" component={Download} />
            <Route path="/about" component={Download} />
            <Route exact path="/details/:id" component={Details} />
            <Route path="/contact" component={Contact} />
            <Route component={ErrorPage} />
          </Switch>
      </div>
    );
  }

然鹅,可能你发现 this.props为{} 空对象
那可能是因为你没有使用withRouter关联组件,关联一下就好了。注意一点,app.js无法关联,withrouter只能关联路由组件或者app.js的子组件

import React, { Component } from "react";
import {withRouter } from "react-router";

class routers extends Component {
 /**
  * 生命周期函数
  */
 // 组件挂载
 componentDidMount() {
   console.log(this.props.location);
 }
 render() {
   return (
     <div key={this.props.location.key}>
     </div>
   );
 }
}
export default withRouter(routers);

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值