[英]useEffect with exhaustive deps loop
When modal.error
sets to true
, then my effect should be run:当
modal.error
设置为true
,应该运行我的效果:
useEffect(() => {
if (modal.error) {
setModal({...modal, prompt: false})
}
}, [modal]);
modal - is an object: modal - 是一个对象:
const [modal, setModal] = useState<SomeInteface>({
success: false,
error: false,
prompt: false
})
However i want in useEffect
deps only modal.error
, but when i do so, linter warns me about exhaustive/deps annoying rule, why should i put my entire object in to a deps array, instead of just one of its properties.但是,我只希望在
useEffect
deps 中使用modal.error
,但是当我这样做时,linter 会警告我有关详尽/ deps 烦人的规则,为什么我要将整个对象放入 deps 数组,而不仅仅是它的一个属性。 It's obviously going for infinite loops, because object modal
is always going to change.这显然是无限循环,因为对象
modal
总是会改变。
I still don't get, why did React team went away from lifecycle's paradigm which was so convenient instead of this 3 in one thing, which is more confusing with these exhaustive/deps rules, i've read a lot of articles about useEffect
, but still, i think lifecycles is much better.我仍然不明白,为什么 React 团队放弃了如此方便的生命周期范式,而不是这
useEffect
,这对这些详尽的/deps 规则更令人困惑,我已经阅读了很多关于useEffect
的文章,但是,我仍然认为生命周期要好得多。
UPDATE 1更新 1
const removePartner = (): void => {
setModal({
...modal,
prompt: false
});
deleteRequest(undefined, modal.id).then((resp: any) => {
if (resp) {
setModal({ ...modal, success: true });
} else {
setModal({ ...modal, error: true });
}
});
};
UPDATE 2更新 2
TSX part:多伦多证券交易所部分:
<Swal
show={modal.prompt}
icon={Icons.warning}
title="Warning!"
text="Are you sure?"
cancelButton={true}
onModalClose={() => setModal({ ...modal, prompt: false })}
onAccept={removePartner}
/>
<Swal
show={modal.error}
icon={Icons.error}
title="Error"
text={fetchError!}
onModalClose={() => setModal({ ...modal, error: false })}
/>
<Swal
show={modal.success}
icon={Icons.success}
title="Success!"
text="You have removed a user!"
onModalClose={() => {
setModal({ ...modal, success: false });
doFetch().then();
}}
/>
I think you don't need an useEffect.我认为你不需要 useEffect。 You just need to bind your state to the modal.
您只需要将您的状态绑定到模态。
<Modal open={modal.error} />
You just need a condition to set the state of modal.error你只需要一个条件来设置 modal.error 的状态
I changed my mind about using objects in useState
hooks, they are meant for a primitive values, that makes sense, otherwise i recommended others to use useReducer
for complex objects.我改变了在
useState
钩子中使用对象的useState
,它们用于原始值,这是有道理的,否则我建议其他人将useReducer
用于复杂对象。 Then you won't have issues with useEffect
deps loops cause of the whole object changes.那么你就不会
useEffect
deps 循环导致整个对象更改的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.