gpt4 book ai didi

dependencies - 使用 useEffect 和 useState 避免 ESLint 'react-hooks/exhaustive-deps' 警告

转载 作者:行者123 更新时间:2023-12-04 10:26:32 46 4
gpt4 key购买 nike

我正在使用 useEffect()通过“useState”调用更新某些状态的钩子(Hook):

useEffect(
() => {
const newProps = {}

departments.forEach(dept => {
const { code } = dept
const newCode = code.toLowerCase()
newProps[newCode + '_reviewer'] = ''
})

setFormValues({ ...formValues, ...newProps })
},
[departments]
)

不出所料,ESLint 给了我一个警告 formValues :
React Hook useEffect has a missing dependency: 'formValues'. 

但是,它继续提到:
Either include it or remove the dependency array.
You can also do a functional update 'setFormValues(f => ...)'
if you only need 'formValues' in the 'setFormValues' call

react-hooks/exhaustive-deps

我对神秘的“setFormValues(f => ...)”方法很感兴趣。这到底是什么意思?我应该如何重写 setFormValues({ ...formValues, ...newProps })为了避免 ESLint 警告, 没有 添加 formValues作为依赖或添加 // eslint-disable-next-line react-hooks/exhaustive-deps ?

我试过查看 repo,我最接近的是 this ,这似乎没有提到这个特殊的解决方法。

最佳答案

您可以将一个函数传递给以该状态的当前值作为第一个参数的 set 函数,并将该状态设置为您在该函数中返回的值。

所以你可以改为:

setFormValues(fValues => ({...fValues, ...newProps}));

并且当您不使用 formValues 状态的任何地方 useEffect 时,您可以避免将其添加到 deps 数组

关于dependencies - 使用 useEffect 和 useState 避免 ESLint 'react-hooks/exhaustive-deps' 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60620248/

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