I am here to ask something about react hooks and missing dependencies .(我在这里问一些关于反应挂钩和缺少依赖项的问题 。)
I try to be concise, this is warning message I have in my console(我尽量保持简洁,这是控制台中显示的警告消息)
Compiled with warnings.
./src/views/categories/Categories.tsx
Line 14:6: React Hook useEffect has a missing dependency: 'dispatcher'. Either include it or remove the dependency array react-hooks/exhaustive-deps
the code of the hook useEffect(挂钩的代码useEffect)
const [categoriesList, dispatcher] = useCategoryList({})
useEffect(() => {
!isOpenConfirmAddModal && dispatcher.fetchCategories()
}, [isOpenConfirmAddModal])
and this is the code of the custom hook useCategoryList(这是自定义钩子useCategoryList的代码)
export const useCategoryList = (
initialState: CategoriesData
): CategoriesListHook => {
const [state, dispatch] = useReducer(categoryReducer, initialState)
const fetchCategories = async () => {
const categories = await getCategories()
dispatch({ type: FETCH_CATEGORIES, data: categories })
}
// ....
return [
state,
{
fetchCategories
// ...
}
]
}
if I set the dispatcher as dependency(如果我将调度程序设置为依赖项)
useEffect(() => {
!isOpenConfirmAddModal && dispatcher.fetchCategories()
}, [isOpenConfirmAddModal, dispatcher])
and the effect in the application is an eternal loop of call to dispatcher.fetchCategories()
, it seems that dispatch
is constantly updating itself and the loop is never ending.(并且在应用程序中的效果是对dispatcher.fetchCategories()
的永恒调用循环,似乎dispatch
在不断更新自身,并且循环永无休止。)
I tried some other coouple of attempts suggested in SO, but I never saw a dispatcher from a useReducer within a useEffect .(我尝试了SO中建议的其他尝试,但从未在useEffect中看到来自useReducer的调度 程序 。)
Ideas, thanks!(想法,谢谢!)
ask by axel translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…