javascript - React Hook useEffect 缺少依赖项 : 'notes' , 如何修复它?

标签 javascript reactjs react-native graphql

我在这里使用了react hook,但我不断收到此错误。

React Hook useEffect has a missing dependency: '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

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();
    };
  }, []);

最佳答案

在您的代码末尾有一个 }, [])

如果您希望通过更改某些 Prop 或状态来更新 useEffect ,您可以在该数组中提及它,例如 }, [props.sth]) 如果您愿意每次您需要删除该空数组时都会调用 useEffect ,并且您的代码将以如下方式结束: })

关于javascript - React Hook useEffect 缺少依赖项 : 'notes' , 如何修复它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59151397/

相关文章:

javascript - React Native 组件没有从 Redux 获取 this.props.dispatch

javascript - 在reactjs和redux中保存和编辑帖子

javascript - 从 typescript 对象中查找具有填充值的属性名称

javascript - 使用 jquery 获取/设置最后打开的 li 的索引

javascript - 检测文本是否溢出

android - 尝试调试 React Native 应用程序时如何解决 NetworkError?

javascript - React 单元测试、 enzyme /摩卡测试(或模拟?)html 图像 api

reactjs - 无法覆盖react-native的TextInput默认填充

node.js - Npm/Yarn 未正确安装并出现问题

c# - 使用 Azure Web 部署时保存到 Azure 根文件夹