react路由返回時不刷新如何解決

這篇文章主要介紹“react路由返回時不刷新如何解決”的相關(guān)知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“react路由返回時不刷新如何解決”文章能幫助大家解決問題。

創(chuàng)新互聯(lián)公司是一家專注于成都網(wǎng)站制作、成都做網(wǎng)站與策劃設(shè)計,順平網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)10多年,網(wǎng)設(shè)計領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:順平等地區(qū)。順平做網(wǎng)站價格咨詢:18982081108

react路由返回時不刷新的解決辦法:1、在路由組件上最上層元素上加一個key增加路由的識別度;2、將key綁定在路由頂層元素上,精確定位路由;3、使用withRouter關(guān)聯(lián)下組件即可。

react 跳轉(zhuǎn)后路由變了頁面沒刷新的解決方案

最近在學(xué)習(xí)React的過程中遇到了路由跳轉(zhuǎn)后頁面不刷新的問題,本文就詳細(xì)的介紹一下解決方法,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

問題

這樣的問題貌似原因還挺多的,我的問題是帶參數(shù)的url不能刷新,router 5.0版本 ,使用withRouter關(guān)聯(lián)組件進行頁面跳轉(zhuǎn)

如下所示

react路由返回時不刷新如何解決

路由代碼

react路由返回時不刷新如何解決

解決方案

在路由組件上最上層元素上加一個key增加路由的識別度,因為普通的跳轉(zhuǎn)是根據(jù)path來識別的,但是path帶上參數(shù)時,路由無法精確識別。不過,在跳轉(zhuǎn)頁面的時候,每個地址都會在localtion對象里添加一個key。如下打印

// 組件掛載
 componentDidMount() {
   console.log(this.props.location);
 }

react路由返回時不刷新如何解決

我們將這個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ā)現(xiàn) this.props為{} 空對象

那可能是因為你沒有使用withRouter關(guān)聯(lián)組件,關(guān)聯(liá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);

關(guān)于“react路由返回時不刷新如何解決”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點。

標(biāo)題名稱:react路由返回時不刷新如何解決
當(dāng)前網(wǎng)址:http://muchs.cn/article10/gdcjgo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、用戶體驗、電子商務(wù)、虛擬主機品牌網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站優(yōu)化排名