react路由返回时不刷新的解决办法:1、在路由组件上最上层元素上加一个key增加路由的识别度;2、将key绑定在路由顶层元素上,精确定位路由;3、使用withrouter关联下组件即可。
本教程操作环境:windows10系统、react18.0.0版、dell g3电脑。
react路由返回时不刷新怎么办?
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);
推荐学习:《react视频教程》
以上就是react路由返回时不刷新怎么办的详细内容。