gpt4 book ai didi

reactjs - react ,ESLint : eslint-plugin-react-hooks shows incorrect "missing dependency"

转载 作者:行者123 更新时间:2023-12-02 03:09:34 30 4
gpt4 key购买 nike

假设您正在使用 React 并且正在编写一个自定义钩子(Hook) useSomething,每次为同一组件调用它时都会返回相同的内容。

const something = useSomething()

// useSomething() at time X === useSomething() at time Y

如果您现在在 useEffect(() => ...) 中使用此 something 值,并且不传递 something作为对 useEffect 第二个参数数组的依赖,那么 linter 会警告您:

React Hook useEffect has a missing dependency: 'something'. Either include it or remove the dependency array. (react-hooks/exhaustive-deps)

当然,ESLint 无法知道 something 将始终保持相同(每个组件),但是将诸如 something 之类的不变事物添加到 useEffect 的依赖项数组中 每次使用它们真的很烦人。仅停用 react-hooks/exhaustive-deps 似乎也不是一个好的解决方案(也不使用 //eslint-disable-next-line react-hooks/exhaustive-deps).

有没有更好的解决方案,而不是为了让 Linter 满意而将不必要的东西添加到 useEffect 的依赖数组中?

请在此处找到一个简单的演示: https://codesandbox.io/s/sad-kowalevski-yfxcn [编辑:请注意,问题是关于上面描述的一般模式,而不是关于这个愚蠢的小演示 ​​- 这个演示的目的只是显示 ESLint 警告,没有别的]

[编辑]请在此处找到附加演示: https://codesandbox.io/s/vibrant-tree-0cyn1

最佳答案

这里

https://github.com/facebook/react/issues/14920#issuecomment-471070149

例如,您可以阅读以下内容:

If it truly is constant then specifying it in deps doesn't hurt. Such as the case where a setState function inside a custom Hook gets returned to your component, and then you call it from an effect. The lint rule isn't smart enough to understand indirection like this. But on the other hand, anyone can wrap that callback later before returning, and possibly reference another prop or state inside it. Then it won’t be constant! And if you fail to handle those changes, you’ll have nasty stale prop/state bugs. So specifying it is a better default.

因此,也许只是将不变的值添加到 useEffect 的依赖数组中可能是最好的解决方案。尽管如此,我还是希望有类似 ESLint react-hooks 配置的可能性来定义一个钩子(Hook)名称列表,其返回值应被视为静态。

关于reactjs - react ,ESLint : eslint-plugin-react-hooks shows incorrect "missing dependency",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58038252/

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