useCallback
对于记住要传递给子组件的功能很有用,但是如果要在循环中渲染这些子组件怎么办?例如
const setBlockedDate = useCallback(idx => ev => {
setBlockedDates(bd => arraySplice(bd,idx,1,[ev.value]));
},[setBlockedDates])
...
{blockedDates.map((bd,idx) => <VehicleBlockedDate
key={bd[REACT_KEY]}
defaultValue={bd}
onChange={setBlockedDate(idx)}
onDelete={deleteBlockedDate(idx)}
reasons={[]}/>)}
useCallback
只会记住外部功能,而不会记住内部功能。这个模式有辅助功能吗?因为我认为这是不对的:
const setBlockedDate = useCallback(idx => useCallback(ev => {
setBlockedDates(bd => arraySplice(bd,idx,1,[ev.value]));
},[setBlockedDates]),[setBlockedDates])
答案 0 :(得分:0)
我认为,这是正确的:
function useArrayCallback(fn, deps = []) {
return useMemo(() => memoize(idx => (...args) => fn(idx, ...args)), deps);
}
memoize
在哪里:
function memoize(fn, options={
serialize: fn.length === 1 ? x => x : (...args) => JSON.stringify(args),
}) {
const cache = new Map();
return (...args) => {
const key = options.serialize(...args);
if(cache.has(key)) {
return cache.get(key);
}
const value = fn(...args);
cache.set(key, value);
return value;
}
}
或者您可以使用一些内置的预先准备好的备注功能。
然后原始问题中的回调可以写为:
const setBlockedDate = useArrayCallback((idx,ev) => {
setBlockedDates(bd => arraySplice(bd,idx,1,[ev.value]));
})