You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

大前端面试题:如何理解通用memoization函数中的resolver参数

通用memo函数中resolver参数作用讲解

resolver的本质是自定义缓存key生成规则的函数。记忆化(memoization)的核心逻辑是将函数的入参和执行结果做映射存储,下次传入相同入参时直接返回缓存结果,无需重复执行,resolver就是用来根据调用时的入参生成对应缓存key的规则。

默认resolver的行为

代码中给出的默认resolver为(...args) => args.join('_'),会把所有入参转成字符串后以下划线拼接作为缓存key,该规则仅在入参都是基础类型(数字、字符串、布尔值等)时能正常工作。

自定义resolver的使用场景

默认规则无法覆盖所有业务场景,出现以下情况时需要自定义resolver:

  • 入参包含引用类型(对象、数组、函数等):默认的join操作会把引用类型统一转为[object Object]之类的固定字符串,导致不同入参生成相同的key,缓存逻辑完全失效
  • 不需要用全部入参判断缓存是否命中:比如函数部分参数不影响执行结果,你可以只提取关键参数生成key

实际用法示例

我们以计算两个矩形面积之和的函数为例,对比不同resolver的效果:

// 要缓存的业务函数
const getTotalArea = (rect1, rect2) => rect1.width * rect1.height + rect2.width * rect2.height

默认resolver的问题

// 使用默认resolver生成记忆化函数
const memoedGetTotalArea_default = memo(getTotalArea)

const rectA = {width: 10, height: 20}
const rectB = {width: 5, height: 5}
// 首次调用生成缓存key为"[object Object]_[object Object]",缓存结果为225
memoedGetTotalArea_default(rectA, rectB) 

const rectC = {width: 1, height: 1}
const rectD = {width: 2, height: 2}
// 再次调用生成的key和之前完全相同,错误返回225而非正确结果5
memoedGetTotalArea_default(rectC, rectD) 

自定义resolver解决问题

// 自定义resolver:提取两个矩形的宽高拼接为key
const customResolver = (r1, r2) => `${r1.width}_${r1.height}_${r2.width}_${r2.height}`
const memoedGetTotalArea_custom = memo(getTotalArea, customResolver)

memoedGetTotalArea_custom(rectA, rectB) // 生成key"10_20_5_5",缓存结果225
memoedGetTotalArea_custom(rectC, rectD) // 生成key"1_1_2_2",正确返回计算结果5

内容的提问来源于stack exchange,提问作者klondike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 21:57:03