![](/img/trans.png)
[英]React Hook useEffect has a missing dependency: 'formData'. Either include it or remove the dependency array. what is dependency is use
[英]React Hook useEffect has a missing dependency: 'reduxArray'. Either include it or remove the dependency array
当数据发生如下变化时,我需要调用 useEffect,
useEffect(()=>{
const filteredData = reduxArray.filter(
() => // do something
);
store.dispatch(method({reduxArray:[...filteredData]}))
},[data])
这实际上满足了我的要求并且对我来说很好,但是 Eslint 对此并不满意,并且给了我错误React Hook useEffect has a missing dependency: 'reduxArray'。 要么包含它,要么删除依赖数组。
在这种情况下,如果我在依赖数组中添加reduxArray ,那么它会导致 useEffect 中的无限循环,因为我正在更新useEffect中的 reduxArray。 除了禁用 eslint 之外,还有其他方法可以克服这个问题吗?
我不知道这是否是一个好的解决方案,但如果你想删除 eslint 警告,那么只需使用
useEffect(()=>{
const filteredData = reduxArray.filter(() => // do something);
store.dispatch(method({reduxArray:[...filteredData]}))
// eslint-disable-next-line react-hooks/exhaustive-deps
},[data])
我喜欢的一个解决方案是在 function 中使用 useCallback,这将防止无限循环。
const handleChangeData = useCallback (() => {
const filteredData = reduxArray.filter();
store.dispatch(method({reduxArray:[...filteredData]}))
},[data,reduxArray])
useEffect(()=>{
handleChangeData
},[handleChangeData])
这个问题的一个解决方案是useEvent
钩子:
const filterData = useEvent(()=>{
const filteredData = reduxArray.filter(
() => // do something
);
store.dispatch(method({reduxArray:[...filteredData]}))
})
useEffect(()=>{
filterData()
},[data])
通过在更新 redux 阵列后简单地保留一个标志来解决它,我不确定这是否是正确的方法,
useEffect(()=>{
const filteredData = reduxArray.filter(
() => // do something
);
if(!flag) {
store.dispatch(method({reduxArray:[...filteredData]}))
}
setFlag(true); // so that it doesn't reupdate infinite times
},[data])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.