reactjs - 我们在 useEffect 中使用的所有变量都在依赖项数组中吗?
问题描述
我知道 useEffect 的依赖项是如何工作的。但是在我的场景中,我不应该看到 prop 值的变化,我将其用作处理流程的条件,但如果我不将其放入依赖项数组中,我将收到 react-hooks/exhaustive-deps 警告。
我的情况是,如果 foo 和 fetchValue 发生变化,我想重新运行整个 fetch。虽然我使用 bar 作为条件来决定调用的是 fechValue,但在我的业务逻辑中,bar 的更改不应该使重新运行块。
const Component = ({ foo, bar, fetchValue }) => {
useEffect = (
() => {
if(foo) {
if (bar) {
fetchValue();
}
}
},
[foo, fetchValue] // will get a warning `react-hooks/exhaustive-deps`
)
return <div />
}
解决方案
ESLint 规则的存在是为了提供useEffect
钩子的安全性。
如果您绝对确定该值不是 的依赖项useEffect
,则可以添加注释以忽略 ESLint 规则:Disabling Rules with Inline Comments。
我建议添加// eslint-disable-next-line
而不是 file-wide eslint-disable
。
有什么方法可以专门针对使用扩展运算符的地方禁用此规则?
// eslint-disable-next-line react-hooks/exhaustive-deps
如果你认为你知道你在做什么,你总是可以的。
推荐阅读
- r - 如何修复为数据框提供的“无效的‘dimnames’?
- html - 我无法控制的 HTML 中的 ASCII 艺术
- java - 在运行时查找包中的所有类(并调用静态方法)
- javascript - Javascript Set has() 方法的行为因我定义传入参数的方式而异
- docker - 并不总是创建中间容器
- ios - 使用 Combine 和 SwiftUI 显示变化值的最简洁方式是什么?
- regex - 正则表达式在 html 注释中查找和替换字符
- python - 用于守望台的“docker run”命令的 Python 脚本
- android - 如何将 FCM 插入房间数据库?
- kubernetes-helm - Helm chart 将 shell 脚本从本地机器复制到远程 pod ,更改权限并执行