react 跳转后路由变了页面没刷新的解决方案

2022-04-15 0 1,132
目录
  • 问题
  • 解决方案

问题

这样的问题貌似原因还挺多的,我的问题是带参数的url不能刷新,router 5.0版本 ,使用withRouter关联组件进行页面跳转
如下所示

react 跳转后路由变了页面没刷新的解决方案

路由代码

react 跳转后路由变了页面没刷新的解决方案

解决方案

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

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

react 跳转后路由变了页面没刷新的解决方案

我们将这个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);

到此这篇关于react 跳转后路由变了页面没刷新的解决方案的文章就介绍到这了,更多相关react 跳转后页面没刷新内容请搜索NICE源码以前的文章或继续浏览下面的相关文章希望大家以后多多支持NICE源码!

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 JavaScript react 跳转后路由变了页面没刷新的解决方案 https://www.niceym.com/29290.html