我最终从各种答案中吸取了一点点,为此制作了自己的钩子。我希望能够删除一些东西来代替,以便快速调试触发的依赖关系。useEffect
useEffect
const usePrevious = (value, initialValue) => {
const ref = useRef(initialValue);
useEffect(() => {
ref.current = value;
});
return ref.current;
};
const useEffectDebugger = (effectHook, dependencies, dependencyNames = []) => {
const previousDeps = usePrevious(dependencies, []);
const changedDeps = dependencies.reduce((accum, dependency, index) => {
if (dependency !== previousDeps[index]) {
const keyName = dependencyNames[index] || index;
return {
...accum,
[keyName]: {
before: previousDeps[index],
after: dependency
}
};
}
return accum;
}, {});
if (Object.keys(changedDeps).length) {
console.log('[use-effect-debugger] ', changedDeps);
}
useEffect(effectHook, dependencies);
};
下面是两个示例。对于每个示例,我假设从“foo”更改为“bar”。示例 1 显示了不通过的输出,示例 2 显示了一个带有 .dep2
dependencyNames
dependencyNames
示例 1
以前:
useEffect(() => {
// useEffect code here...
}, [dep1, dep2])
后:
useEffectDebugger(() => {
// useEffect code here...
}, [dep1, dep2])
控制台输出:
{
1: {
before: 'foo',
after: 'bar'
}
}
对象键“1”表示已更改的依赖项的索引。此处已更改,因为它是依赖项中的第 2 项或索引 1。dep2
示例 2
以前:
useEffect(() => {
// useEffect code here...
}, [dep1, dep2])
后:
useEffectDebugger(() => {
// useEffect code here...
}, [dep1, dep2], ['dep1', 'dep2'])
控制台输出:
{
dep2: {
before: 'foo',
after: 'bar'
}
}