【发布时间】:2020-03-27 19:15:33
【问题描述】:
我在这里使用了 react hook,但我一直收到这个错误。
React Hook useEffect 缺少一个依赖项:'notes'。要么包括 它或删除依赖数组。您还可以进行功能更新 'setNotes(n => ...)' 如果你在 'setNotes' 调用中只需要 'notes' 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();
};
}, []);
【问题讨论】:
-
在
updateNoteListner中,您指的是notes而不是prevNotes。相信没有什么特殊原因,只是一个错字
标签: javascript reactjs react-native graphql