gpt4 book ai didi

reactjs - 如何在 react 中处理自定义 Hook 的依赖关系数组

转载 作者:行者123 更新时间:2023-12-03 13:16:57 26 4
gpt4 key购买 nike

我正在创建一个自定义 Hook ,并希望定义一个可选参数,以便我可以在需要时传递额外的依赖项。我的代码如下所示:

import { useEffect } from 'react';

function useCustomHook(param1, extraDeps) {
useEffect(() => {
// do something with param1 here
}, [param1, ...extraDeps])
}

react-hooks/exhaustive-deps 抛出警告说

React Hook useEffect has a spread element in its dependency array. This means we can't statically verify whether you've passed the correct dependencies

有人知道如何解决该警告吗?或者将 deps 数组传递给自定义钩子(Hook)不是一个好习惯?

对于那些对为什么需要 extraDeps 感兴趣的人。这是一个例子:

const NewComponent = (props) => {
[field1, setField1] = useState()
[field2, setField2] = useState()

// I only want this to be called when field1 change
useCustomHook('.css-selector', [field1]);

return <div>{field1}{field2}</div>;
}

最佳答案

我找到了此处提出的解决方案的有用替代方案。如前所述in this Reddit topic ,React 团队显然推荐了类似的东西:

// Pass the callback as a dependency
const useCustomHook = callback => {
useEffect(() => { /* do something */ }, [callback])
};

// Then the user wraps the callback in `useMemo` to avoid running the effect too often
// Whenever the deps change, useMemo will ensure that the callback changes, which will cause effect to re-run
useCustomHook(
useMemo(() => { /* do something */ }, [a, b, c])
);

我已经使用了这种技术并且效果非常好。

关于reactjs - 如何在 react 中处理自定义 Hook 的依赖关系数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56262515/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com