React-router?v6在Class組件和非組件代碼中的正確使用
最近內(nèi)部正在開發(fā)的 react 項目 react-router 全線升級到了 v6 版本
v6 版本中很多 API 進(jìn)行了重構(gòu)變更,導(dǎo)致很多舊寫法失效
下面記錄一下 history 模塊在 v6 中的用法
在封裝的request等非組件代碼中如何使用 history 進(jìn)行路由?
1. history路由用法
將 createBrowserHistory() 創(chuàng)建的 history 與新的 unstable_HistoryRouter API進(jìn)行上下文綁定
注意:
在 v6 版本中如果不對上下文進(jìn)行綁定直接使用 createBrowserHistory() 創(chuàng)建的 history 進(jìn)行編程式路由操作
將出現(xiàn)路由變化 UI 不變化的問題,hash 和 history 模式同理。
import { createBrowserHistory } from 'history';
import { unstable_HistoryRouter as HistoryRouter } from 'react-router-dom';
let history = createBrowserHistory();
function App() {
return (
<HistoryRouter history={history}>
// The rest of your app
</HistoryRouter>
);
}
history.push("/foo");
2. hash路由用法
import HashHistory from 'history/hash';
import { unstable_HistoryRouter as HistoryRouter } from 'react-router-dom';
function App() {
return (
<HistoryRouter history={HashHistory}>
// The rest of your app
</HistoryRouter>
);
}
history.push("/foo");
項目升級了v6版本,怎么兼容舊的Class組件?
使用新的 hooks API封裝高階組件包裹 class 組件進(jìn)行 props 的傳遞
import {
useLocation,
useNavigate,
useParams,
} from "react-router-dom";
function withRouter(Component) {
function ComponentWithRouterProp(props) {
let location = useLocation();
let navigate = useNavigate();
let params = useParams();
return (
<Component
{...props}
router={{ location, navigate, params }}
/>
);
}
return ComponentWithRouterProp;
}
// class components
@withRouter()
class YouClassComponent extends React.Component {}
export default YouClassComponent
// or
class YouClassComponent extends React.Component {}
export default withRouter(YouClassComponent)
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Remix后臺開發(fā)之remix-antd-admin配置過程
這篇文章主要為大家介紹了Remix后臺開發(fā)之remix-antd-admin配置過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
詳解Jotai Immer如何實現(xiàn)undo redo功能示例詳解
這篇文章主要為大家介紹了詳解Jotai Immer如何實現(xiàn)undo redo功能示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
React Native中TabBarIOS的簡單使用方法示例
最近在學(xué)習(xí)過程中遇到了很多問題,TabBarIOS的使用就是一個,所以下面這篇文章主要給大家介紹了關(guān)于React Native中TabBarIOS簡單使用的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下。2017-10-10
React-Router如何進(jìn)行頁面權(quán)限管理的方法
本篇文章主要介紹了React-Router如何進(jìn)行頁面權(quán)限管理的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12
react配合antd組件實現(xiàn)的管理系統(tǒng)示例代碼
這篇文章主要介紹了react配合antd組件實現(xiàn)的管理系統(tǒng)示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04

