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 不变化的问题,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 组件进行 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)
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Remix后台开发之remix-antd-admin配置过程
这篇文章主要为大家介绍了Remix后台开发之remix-antd-admin配置过程详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-04-04
详解Jotai Immer如何实现undo redo功能示例详解
这篇文章主要为大家介绍了详解Jotai Immer如何实现undo redo功能示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-04-04
React Native中TabBarIOS的简单使用方法示例
最近在学习过程中遇到了很多问题,TabBarIOS的使用就是一个,所以下面这篇文章主要给大家介绍了关于React Native中TabBarIOS简单使用的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下。2017-10-10


最新评论