[英]ESLint wants setSate as a dependency for useEffect but this causes an infinite loop (react-hooks/exhaustive-deps)
I have the following situation:我有以下情况:
const [values, setValues] = useState({
username: "",
password: ""
});
const [submitButton, setSubmitButton] = useState({
disabled: true
});
useEffect(() => {
const disabled = !(values.username.length && values.password.length);
setSubmitButton({ ...submitButton, disabled });
}, [values]);
This works perfectly fine and does exactly what I would like but ESLint complains with react-hooks/exhaustive-deps
warning.这工作得很好,完全符合我的要求,但 ESLint 抱怨
react-hooks/exhaustive-deps
警告。
When I do eslint autofix, it adds setSubmitButton
as a dependency to useEffect, however that causes an infinite loop.当我执行 eslint autofix 时,它会添加
setSubmitButton
作为setSubmitButton
的依赖项,但这会导致无限循环。 This seems like such a simple situation but I can't figure out what I'm doing wrong.这似乎是一个如此简单的情况,但我无法弄清楚我做错了什么。 I've seen code of other people that use setState and the like within useEffect without declaring it as a dependency.
我已经看到其他人的代码在 useEffect 中使用 setState 等,但没有将其声明为依赖项。
You should use the functional updater form of useState
, which will provide a snapshot of your state, thus eliminating the need for directly reference it.您应该使用
useState
的功能更新程序形式,它将提供您状态的快照,从而无需直接引用它。
setSubmitButton(previous => ({ ...previous, disabled }));
Since React
already knows the current value of submitButton
and will only run the callback when changing the state this will happen outside your component's scope and eslint
won't be mad at you.由于
React
已经知道submitButton
的当前值,并且只会在更改状态时运行回调,这将发生在组件范围之外,并且eslint
不会生你的气。 In Dan's words用丹的话说
I like to think of these cases as “false dependencies”.
我喜欢将这些情况视为“虚假依赖”。 Yes, count was a necessary dependency because we wrote setCount(count + 1) inside the effect.
是的,count 是一个必要的依赖,因为我们在 effect 中写了 setCount(count + 1)。 However, we only truly needed count to transform it into count + 1 and “send it back” to React.
然而,我们只需要真正需要 count 将其转换为 count + 1 并将其“发送回”到 React。 But React already knows the current count.
但是 React 已经知道当前的计数。 All we needed to tell React is to increment the state — whatever it is right now.
我们需要告诉 React 的只是增加状态——不管它现在是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.