vite4加react18加ts-安装篇; 最近从vue3转型学习了,react相关技术架构,去有意识的去学习了相关东西,内容比较实用,没有引入太多原理和概念,就是最直接最实用的记录下来;
GitHbu
https://github.com/CJY0208/react-activation/blob/d489c524282a61974805b7504d30acff01088892/README_CN.md
安装react-activation
npm install react-activation
项目中版本
"react-activation": "^0.12.2",
组件中使用
import { useState } from 'react'
import KeepAlive from 'react-activation'
function Counter() {
const [count, setCount] = useState(0)
return (
<div>
<p>count: {count}</p>
<button onClick={() => setCount(count => count + 1)}>Add</button>
</div>
)
}
function App() {
const [show, setShow] = useState(true)
return (
<div>
<button onClick={() => setShow(show => !show)}>Toggle</button>
{show && (
<KeepAlive>
<Counter />
</KeepAlive>
)}
</div>
)
}
export default App
路由中使用
// 在入口处使用<AliveScope>组件包裹页面
import React from 'react'
import ReactDOM from 'react-dom'
import { AliveScope } from 'react-activation'
import App from './App'
ReactDOM.render(
<AliveScope>
<App />
</AliveScope>,
document.getElementById('root')
)
// 注册路由时
const generateRouter = (routers:any) => {
return routers.map((item:any) => {
if (item.children) {
item.children = generateRouter(item.children)
}
item.element = <KeepAlive id={item.path} name="Test">
<Suspense>
<item.component/>
</Suspense>
</KeepAlive>
return item
})
}
卸载方法
import { withAliveScope, useAliveController } from 'react-activation';
/*
1.给需要控制缓存的 <KeepAlive /> 标签增加 name 属性
2.使用 withAliveScope 或 useAliveController 获取控制函数
drop(name):注意,仅卸载命中的第一层内容,不会卸载嵌套的、未命中的
dropScope(name):将卸载所有内容包括嵌套内容
refresh(name): 仅刷新命中第一层内容,不会刷新嵌套内容
refreshScope(name): 将刷新所有内容,包括嵌套内容
clear(): 清空所有缓存
getCachingNodes(): 获取所有缓存中的节点
*/
const { drop, dropScope, refresh,
refreshScope, clear, getCachingNodes } = useAliveController();