[英]React Hook useEffect has a missing dependency: 'notes', how to fix it?
I have used react hook here,ani I keep getting this error.我在这里使用了 react hook,ani 我一直收到这个错误。
React Hook useEffect has a missing dependency: 'notes'.
React Hook useEffect 缺少一个依赖项:'notes'。 Either include it or remove the dependency array.
包括它或删除依赖项数组。 You can also do a functional update 'setNotes(n => ...)' if you only need 'notes' in the 'setNotes' call react-hooks/exhaustive-deps
如果您只需要在“setNotes”调用中的“notes”,您还可以进行功能更新“setNotes(n => ...)” react-hooks/exhaustive-deps
useEffect(() => {
getNotes();
const createNoteListner = API.graphql(
graphqlOperation(onCreateNote)
).subscribe({
next: noteData => {
const newNote = noteData.value.data.onCreateNote;
setNotes(prevNotes => {
const oldnotes = prevNotes.filter(note => note.id !== newNote.id);
const updatedNotes = [...oldnotes, newNote];
return updatedNotes;
});
setNote("");
}
});
const deleteNoteListner = API.graphql(
graphqlOperation(onDeleteNote)
).subscribe({
next: noteData => {
const deleteNote = noteData.value.data.onDeleteNote;
setNotes(prevNotes => {
const updatedNotes = prevNotes.filter(
note => note.id !== deleteNote.id
);
return updatedNotes;
});
}
});
const updateNoteListner = API.graphql(
graphqlOperation(onUpdateNote)
).subscribe({
next: noteData => {
const updatedNote = noteData.value.data.onUpdateNote;
setNotes(prevNotes => {
const index = prevNotes.findIndex(note => note.id === updateNote.id);
const updatedNotes = [
...notes.slice(0, index),
updatedNote,
...notes.slice(index + 1)
];
return updatedNotes;
});
setNote("");
setId("");
}
});
return () => {
createNoteListner.unsubscribe();
deleteNoteListner.unsubscribe();
updateNoteListner.unsubscribe();
};
}, []);
In your code in the end of your code there is a }, [])
在您的代码末尾的代码中,有一个
}, [])
If you want your useEffect
update by changing some props or state you can mention it in that array for example }, [props.sth])
and if you want your useEffect
call every time you need to remove that empty array and your code will end like : })
如果您希望通过更改某些道具或状态来更新
useEffect
,您可以在该数组中提及它,例如}, [props.sth])
并且如果您希望每次需要删除该空数组时都调用useEffect
并且您的代码将结束喜欢: })
You need to add notes
in the dependencies of your effect If not , changes will not be reflected.您需要在您的效果的依赖项中添加
notes
,否则将不会反映更改。
...
return() =>{
createNoteListner.unsubscribe();
deleteNoteListner.unsubscribe();
updateNoteListner.unsubscribe();
}
}, [notes])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.