React-router v6 在 Class 组件和非组件代码中的正确用法

最近内部正在开发的 react 项目 react-router 全线升级到了 v6 版本,v6 版本中很多 API 进行了重构变更,导致很多旧写法失效,下面记录一下 history 模块在 v6 中的用法。

一. 在封装的 request 等非组件代码中怎么使用 history 进行路由?

1. history 路由用法

createBrowserHistory() 创建的 history 与新的 unstable_HistoryRouter API进行上下文绑定

注意:在 v6 版本中如果不对上下文进行绑定直接使用 createBrowserHistory() 创建的 history 进行编程式路由操作,将出现路由变化 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");

二. 项目升级了 v6 版本,怎么兼容旧的 Class 组件?

使用新的 hooks API封装高阶组件包裹 class 组件进行 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)

PS:后续将对一些常见问题进行补充,有疑问的童孩欢迎留言催更!

你可能感兴趣的:(React全家桶,javascript,react.js,react-router,history)