本教程操作環(huán)境:Windows10系統(tǒng)、react18.0.0版、Dell G3電腦。
(相關(guān)資料圖)
react路由返回時(shí)不刷新怎么辦?
react 跳轉(zhuǎn)后路由變了頁(yè)面沒刷新的解決方案
最近在學(xué)習(xí)React的過程中遇到了路由跳轉(zhuǎn)后頁(yè)面不刷新的問題,本文就詳細(xì)的介紹一下解決方法,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
問題
這樣的問題貌似原因還挺多的,我的問題是帶參數(shù)的url不能刷新,router 5.0版本 ,使用withRouter關(guān)聯(lián)組件進(jìn)行頁(yè)面跳轉(zhuǎn)
如下所示
路由代碼
解決方案
在路由組件上最上層元素上加一個(gè)key增加路由的識(shí)別度,因?yàn)槠胀ǖ奶D(zhuǎn)是根據(jù)path來識(shí)別的,但是path帶上參數(shù)時(shí),路由無法精確識(shí)別。不過,在跳轉(zhuǎn)頁(yè)面的時(shí)候,每個(gè)地址都會(huì)在localtion對(duì)象里添加一個(gè)key。如下打印
// 組件掛載 componentDidMount() { console.log(this.props.location); }
我們將這個(gè)key綁定在 路由頂層元素上就能精確定位路由了
render() { return ( {/*就是這個(gè)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ā)現(xiàn) this.props為{} 空對(duì)象
那可能是因?yàn)槟銢]有使用withRouter關(guān)聯(lián)組件,關(guān)聯(lián)一下就好了。注意一點(diǎn),app.js無法關(guān)聯(lián),withrouter只能關(guān)聯(lián)路由組件或者app.js的子組件
import React, { Component } from "react";import {withRouter } from "react-router"; class routers extends Component { /** * 生命周期函數(shù) */ // 組件掛載 componentDidMount() { console.log(this.props.location); } render() { return ( <div key={this.props.location.key}> </div> ); }}export default withRouter(routers);
推薦學(xué)習(xí):《react視頻教程》
以上就是react路由返回時(shí)不刷新怎么辦的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章!
關(guān)鍵詞: React