javascript - 反应 useEffect 和 useCallback linting 错误 - 缺少依赖项
问题描述
Linter 抱怨缺少作为依赖项的函数,即使我在定义它的父组件中使用推荐的 useCallback 钩子。
有谁知道如何解决这一问题?似乎在任何地方都找不到示例
此处链接到沙箱 https://codesandbox.io/s/hopeful-wind-w4sp5
const arr = ['One', 'Two', 'Three']
const SyncingData = () => {
const [progress, setProgress] = useState(0)
const [children, setChildrenProgress] = useState(arr.map(item => 0))
const handleChildrenProgress = useCallback(
(progress, index) => {
setChildrenProgress(
children.map((item, currIndex) =>
index === currIndex ? progress : item,
),
)
},
[children],
)
useEffect(() => {
setProgress(
children.reduce((sum, item) => (sum = sum + item), 0) / children.length,
)
}, [children])
return (
<div>
<div>Total Progress: {progress}</div>
<ul>
{arr.map((item, index) => (
<Child
key={index}
index={index}
updateProgress={handleChildrenProgress}
name={item}
delay={10 * index}
/>
))}
</ul>
</div>
)
}
const Child = ({updateProgress, name, index, delay}) => {
const [progress, setProgress] = useState(0)
// This is the useEffect the linter doesn't like
useEffect(() => {
updateProgress(progress, index)
}, [progress, index])
useInterval(() => {
if (progress < 100) {
setProgress(progress + 1)
}
}, delay)
return (
<div>
{name} {progress}
</div>
)
}
解决方案
我认为您应该尝试在效果的依赖项列表中添加“updateProgress”:
useEffect(() => {
updateProgress(progress, index)
}, [progress, index, updateProgress])
函数 updateProgress 包含在您提供的 lambda 中。
linter 试图告诉您,如果该函数发生更改,效果将不会考虑该更改。
推荐阅读
- python - 如何将格式 yyyy-mm-ddThh:mm:ss 转换为 unix 时间戳?
- qt - 在没有glOrtho的QOpenGLWidget中放大光标位置
- php - 2个脚本交互获取图片和描述
- typescript - 如何在 TypeScript Playground 中修改 compilerOptions.lib?
- npm - 在哪里获得有关受损 npm 包的警报
- android - 我已经从 WCF 命名空间替换了 tempuri.org,但我可以同时使用吗?
- ios - 在实际 iPhone 上测试时没有触觉反馈
- go - 如何使用golang中的GORM框架将结构数组嵌入另一个结构并将其保存在数据库中
- oracle - 从 Oracle Database 11g 生成表创建脚本
- mysql - 相同的查询和数据结构,但 MySQL 8 与 MySQL 5 返回的结果不同?