• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

react路由返回时不刷新怎么办

武飞扬头像
PHP中文网
帮助80

react路由返回时不刷新怎么办?

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);

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tangbeehg
系列文章
更多 icon
同类精品
更多 icon
继续加载