• 技术文章 >web前端 >前端问答

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

    藏色散人藏色散人2023-01-04 10:11:52原创100

    react路由返回时不刷新的解决办法:1、在路由组件上最上层元素上加一个key增加路由的识别度;2、将key绑定在路由顶层元素上,精确定位路由;3、使用withRouter关联下组件即可。

    本教程操作环境:Windows10系统、react18.0.0版、Dell G3电脑。

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

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

    最近在学习React的过程中遇到了路由跳转后页面不刷新的问题,本文就详细的介绍一下解决方法,需要的朋友们下面随着小编来一起学习学习吧

    问题

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

    如下所示

    5e0d5eb4e7dec7ac09594cf9e6167cd.jpg

    路由代码

    b438e8f1e45f639423b73d1dcb0cca0.jpg

    解决方案

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

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

    ccf4d9823d05a5de15dd779eaa1d45a.jpg

    我们将这个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路由返回时不刷新怎么办的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:React
    上一篇:react有数据但渲染不上怎么办 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • react引入css没有效果怎么办• 10 个编写更简洁React代码的实用小技巧• react安装yarn一直报不是内部命令怎么办• react怎么修改对象的属性值• react有数据但渲染不上怎么办
    1/1

    PHP中文网