react 不像 vue 能使用 keep-alive。当 react 跳到另外一个页面,再返回到上一个页面。上一个页面会重新渲染。由于水平有限,所以决定将接口数据进行缓存。第一次没有缓存会请求。第二次执行方法时判断是否有缓存,有就直接返回缓存的数据。我觉得要理解这个 hook,要明白模块只会被加载一次。还要明白每次 re-render 有些方法是会被重新执行,有些方法是会被重新定义。
useCache hook
interface Cb {
(...arg: unknown[]): unknown
}
const cacheMap = new Map();
export default (key: string, callback: Cb) => {
return async (cache = true) => {
const result = cacheMap.get(key)
if(cache && result) {
return result
}
const res = await callback()
cacheMap.set(key, res)
return res
}
}
使用
/* 堆代码 duidaima.com */
function App () {
const [count, setCount] = useState(0)
useEffect(() => {
fn()
})
async function fn () {
const res = await getStatus()
console.log('===>', res);
}
const getStatus = useCache('getStatus', () => {
const arr = [1,2,3,4]
const res = [] as number[]
arr.forEach(num => {
console.log(num);
res.push(num)
});
return res
})
function add () {
setCount(c => c + 1)
}
return (
<>
<h2>==</h2>
<br />
{count}
<br />
<button onClick={add}>add</button>
<h2>==</h2>
</>
)
}