react 跳轉后路由變了頁面沒刷新的解決方案
問題
這樣的問題貌似原因還挺多的,我的問題是帶參數的url不能刷新,router 5.0版本 ,使用withRouter關聯(lián)組件進行頁面跳轉
如下所示
路由代碼
解決方案
在路由組件上最上層元素上加一個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ā)現(xiàn) this.props為{} 空對象
那可能是因為你沒有使用withRouter關聯(lián)組件,關聯(lián)一下就好了。注意一點,app.js無法關聯(lián),withrouter只能關聯(lián)路由組件或者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 跳轉后頁面沒刷新內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
react中的useImperativeHandle()和forwardRef()用法
這篇文章主要介紹了react中的useImperativeHandle()和forwardRef()用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08react如何利用useRef、forwardRef、useImperativeHandle獲取并處理dom
這篇文章主要介紹了react如何利用useRef、forwardRef、useImperativeHandle獲取并處理dom,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2023-10-10React組件內事件傳參實現(xiàn)tab切換的示例代碼
本篇文章主要介紹了React組件內事件傳參實現(xiàn)tab切換的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07React-router4路由監(jiān)聽的實現(xiàn)
這篇文章主要介紹了React-router4路由監(jiān)聽的實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08