最近内部正在开发的 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)
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
来源链接:https://www.jb51.net/javascript/317697rb8.htm
© 版权声明
本站所有资源来自于网络,仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您(转载者)自己承担!
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
THE END
暂无评论内容