gpt4 book ai didi

javascript - ESLint 希望 setSate 作为 useEffect 的依赖项,但这会导致无限循环(react-hooks/exhaustive-deps)

转载 作者:行者123 更新时间:2023-12-02 22:19:45 25 4
gpt4 key购买 nike

我有以下情况:

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

这工作得很好,并且完全符合我的要求,但 ESLint 提示 react-hooks/exhaustive-deps 警告。

当我执行 eslint autofix 时,它会添加 setSubmitButton 作为 useEffect 的依赖项,但这会导致无限循环。这看起来是一个简单的情况,但我不知道我做错了什么。我见过其他人在 useEffect 中使用 setState 等代码,但没有将其声明为依赖项。

最佳答案

您应该使用functional updater form useState 的,它将提供您的状态的快照,从而无需直接引用它。

setSubmitButton(previous => ({ ...previous, disabled }));

由于 React 已经知道 submitButton 的当前值,并且只会在更改状态时运行回调,这将发生在组件范围和 eslint 不会生你的气。在 Dan's

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. However, we only truly needed count to transform it into count + 1 and “send it back” to React. But React already knows the current count. All we needed to tell React is to increment the state — whatever it is right now.

Font

关于javascript - ESLint 希望 setSate 作为 useEffect 的依赖项,但这会导致无限循环(react-hooks/exhaustive-deps),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59270989/

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