本教程操作環(huán)境: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> ); }然鵝,可能你發(fā)現 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中文網其它相關文章!
關鍵詞: React