主题
memo
记忆化一个函数
基本用法
用memo包装一个函数,得到一个自动返回已计算值的新函数。
ts
import { memo } from 'radash'
const timestamp = memo(() => Date.now())
const now = timestamp()
const later = timestamp()
now === later // => true
过期时间
你可以选择性地传递一个ttl
(生存时间)参数,用于设置记忆化结果的过期时间。在版本10之前,如果未指定,ttl
的默认值为300毫秒。
ts
import { memo, sleep } from 'radash'
const timestamp = memo(() => Date.now(), {
ttl: 1000 // 毫秒
})
const now = timestamp()
const later = timestamp()
await sleep(2000)
const muchLater = timestamp()
now === later // => true
now === muchLater // => false
键函数
你可以选择性地自定义记忆化时值的存储方式。
ts
const timestamp = memo(({ group }: { group: string }) => {
const ts = Date.now()
return `${ts}::${group}`
}, {
key: ({ group }: { group: string }) => group
})
const now = timestamp({ group: 'alpha' })
const later = timestamp({ group: 'alpha' })
const beta = timestamp({ group: 'beta' })
now === later // => true
beta === now // => false