反应挂钩-索引回调

时间:2019-08-17 22:03:11

标签: reactjs react-hooks memoization

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])

1 个答案:

答案 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]));
})