React + Ant Design Pro项目实现keep-alive页签
背景
PC端管理系統(tǒng),采用?ant design pro?方案,它是阿里的一個管理系統(tǒng)框架,技術(shù)棧是react。
相比vue,react一個先天不足是不支持 keep-alive,所以管理系統(tǒng)中的多頁簽功能難以實現(xiàn)。
調(diào)研
由于官方不支持,只能網(wǎng)上尋找各方大佬的開源插件。
目前選擇的是?umi-plugin-keep-alive?,它是在?react-activation?基礎(chǔ)上,針對阿里自己的?umi?進行的定制化封裝,antd pro 核心也是 umi 技術(shù),所以 umi-plugin-keep-alive 與 antd pro 可以完美搭配。
實現(xiàn)
插件找到了,接下來的難點是對框架的改造。
由于 ant design pro 封裝的很厲害,操作靈活性并不高,以下是改造的一個思路。
1. 創(chuàng)建 BaseLayout 和 BaseTabs 兩個組件
這一步是標簽頁與緩存的實現(xiàn)
// BaseTabs/index.tsx import { Tabs } from 'antd'; import React from 'react'; import { useAliveController, useHistory, useLocation } from 'umi'; const { TabPane } = Tabs;export default (): React.ReactElement => {const { pathname } = useLocation();const history = useHistory();// 獲取緩存列表const { getCachingNodes, dropScope } = useAliveController();const cachingNodes = getCachingNodes();/*** 點擊tab,跳轉(zhuǎn)頁面*/const clickTab = (path: string) => {history.push(path);};/*** 關(guān)閉tab,銷毀緩存*/const editTab = (path: any) => {dropScope(path);// 關(guān)閉當前頁面,需跳轉(zhuǎn)到其他頁簽if (path === pathname) {const index = cachingNodes.findIndex((item) => item.name === path);if (index > 0) {history.push(cachingNodes[index - 1].name as string);} else {history.push(cachingNodes[1].name as string);}}};return (<Tabstype="editable-card"hideAddsize="small"activeKey={pathname}onTabClick={clickTab}onEdit={editTab}>{cachingNodes.map((node) => (<TabPane tab={node.tabName} key={node.name} closable={cachingNodes.length > 1} />))}</Tabs>); }; // BaseLayout/index.tsx import React from 'react'; import { KeepAlive } from 'umi'; import BaseTabs from '../BaseTabs';export default (props: any): React.ReactElement => {const { children, location } = props;const { pathname } = location;return (<><BaseTabs /><KeepAlive id={pathname} name={pathname} tabName={props.route.name}>{children}</KeepAlive></>); };2. 將BaseLayout應(yīng)用起來
這一步被卡了很久,不知道該怎么把功能和框架相關(guān)聯(lián),原來需要在路由配置里加?wrappers 屬性,這個屬性官方文檔中沒有體現(xiàn),翻閱了很多網(wǎng)上案例才找到,代碼如下。(這里是舉個例子,實際可以遍歷 routes統(tǒng)一加屬性)
這樣寫好后,系統(tǒng)就可以自動根據(jù)路由,完成緩存的功能了。?
總結(jié)
以上是生活随笔為你收集整理的React + Ant Design Pro项目实现keep-alive页签的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php数据结构 链表,php数据结构-单
- 下一篇: 好书分享、能量传递-《软技能 代码之外的