react跳轉(zhuǎn)后路由變了頁面沒刷新的解決
問題
這樣的問題貌似原因還挺多的,我的問題是帶參數(shù)的url不能刷新,router 5.0版本 ,使用withRouter關(guān)聯(lián)組件進(jìn)行頁面跳轉(zhuǎn)
如下所示
路由代碼
解決方案
在路由組件上最上層元素上加一個key增加路由的識別度,因為普通的跳轉(zhuǎn)是根據(jù)path來識別的,但是path帶上參數(shù)時,路由無法精確識別。
不過,在跳轉(zhuǎn)頁面的時候,每個地址都會在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ā)現(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);
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
react基于react-slick實現(xiàn)多圖輪播效果
React slick是一個使用React構(gòu)建的輪播組件,下面這篇文章主要給大家介紹了關(guān)于react基于react-slick實現(xiàn)多圖輪播效果的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07React項目開發(fā)中函數(shù)組件與函數(shù)式編程關(guān)系
函數(shù)組件和函數(shù)式編程究竟是什么關(guān)系呢?本文會圍繞這個話題展開講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11react+ant design實現(xiàn)Table的增、刪、改的示例代碼
這篇文章主要介紹了react+ant design實現(xiàn)Table的增、刪、改的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12React?Native中原生實現(xiàn)動態(tài)導(dǎo)入的示例詳解
在React?Native社區(qū)中,原生動態(tài)導(dǎo)入一直是期待已久的功能,在這篇文章中,我們將比較靜態(tài)和動態(tài)導(dǎo)入,學(xué)習(xí)如何原生地處理動態(tài)導(dǎo)入,以及有效實施的最佳實踐,希望對大家有所幫助2024-02-02webpack4+react多頁面架構(gòu)的實現(xiàn)
webpack在單頁面打包上應(yīng)用廣泛,以create-react-app為首的腳手架眾多。這篇文章主要介紹了webpack4+react多頁面架構(gòu)的實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-10-10