下拉列表中的值基于 API 调用,其数组响应存储在 Zustand 存储中。我有一个 useEffect 来侦听当 Zustand 存储变量不再为空时,它会自动将该数组中的第一个值分配为表单中的选定值。
const formik = useFormik()
const store = useZustandStore()
useEffect(() => {
if (store.someSearchItems.length) {
const initial = store.someSearchItems[0].value as string;
formik.setFieldValue('LIST_VALUE', initial);
}
}, [store.someSearchItems]);
它完成了它的工作,但是,我收到错误
React Hook useEffect has a missing dependency: 'formik'. Either include it or remove the dependency array.
如何在不禁用它的情况下解决此 lint 问题?
我尝试在依赖项数组中包含
formik
,但即使表单内不相关的值发生更改,也会执行 useEffect。
你可以这样做:
function listValue(){
const initial = store.someSearchItems[0].value as string;
formik.setFieldValue('LIST_VALUE', initial);
}
useEffect(() => {
if (store.someSearchItems.length) {
listValue();
}
}, [listValue, store.someSearchItems]);
或者,您可以使用以下注释来抑制警告:
// eslint-disable-next-line react-hooks/exhaustive-deps
尽管如此,您可以在此处
了解更多有关其危险原因的信息 useEffect(() => {
if (store.someSearchItems.length) {
const initial = store.someSearchItems[0].value as string;
formik.setFieldValue('LIST_VALUE', initial);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [store.someSearchItems]);