亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

React-router?v6在Class組件和非組件代碼中的正確使用

 更新時(shí)間:2024年03月14日 10:06:03   作者:超喜歡你呦  
這篇文章主要介紹了React-router?v6在Class組件和非組件代碼中的正確使用方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

最近內(nèi)部正在開發(fā)的 react 項(xiàng)目 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 不變化的問題,hashhistory 模式同理。

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");

項(xiàng)目升級了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é)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論