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)

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

来源链接:https://www.jb51.net/javascript/317697rb8.htm

© 版权声明
THE END
支持一下吧
点赞11 分享
评论 抢沙发
头像
请文明发言!
提交
头像

昵称

取消
昵称表情代码快捷回复

    暂无评论内容