0

I am currently making a TodoList app using Recoil and React and I am getting the error:

 Line 45:6:  React Hook useEffect has missing dependencies: 'setTodoList' and 'todoList'. Either include them or remove the dependency array  react-hooks/exhaustive-deps

I believe this is preventing the app from building. It works in development mode.

Please help me fix this!

Here is the concerned file:

export default function Todos() {
  // Global State Hooks
  const [todoList, setTodoList] = useRecoilState(todoState);
  const changing = useRevoilValue(changeState);
  const show = useRecoilValue(addState);
  const removing = useRecoilValue(removeState);
  const priority = useRecoilValue(priorityState);

  // **** CODE SEGMENT STARTS HERE ****

  useEffect(() => {
    if (priority) {
      setTodoList(
        todoList.slice().sort(function (a, b) {
          return a.priority - b.priority; // By priority
        })
      );
    } else {
      setTodoList(
        todoList.slice().sort(function (a, b) {
          return a.title.localeCompare(b.title); // By name
        })
      );
    }
    // Watches priority for sortButton, and editing, adding and deleting modes etc.
  }, [priority, changing, show, removing]);

  // **** CODE SEGMENT ENDS HERE ****

  return (
    <div className={styles.todos}>
      {/* Dynamically render  todo items */}
      {todoList.map((todo, index) => (
        <span key={todo.id} className={styles.todoItem}>
          <TodoItem key={index} item={todo} />
        </span>
      ))}
      {/* Todo Form only appears in adding mode */}
      {show ? <TodoForm /> : null}
    </div>
  );
}
4

2 回答 2

2

这是 React 回馈的警告。因此,React 希望我们使用setTodoListandtodoList是第二个参数数组中的依赖项。

  useEffect(() => {
    if (priority) {
      setTodoList(
        todoList.slice().sort(function (a, b) {
          return a.priority - b.priority; // By priority
        })
      );
    } else {
      setTodoList(
        todoList.slice().sort(function (a, b) {
          return a.title.localeCompare(b.title); // By name
        })
      );
    }
    // Watches priority for sortButton, and editing, adding and deleting modes etc.
  }, [priority, changing, show, removing,todoList,setTodoList]); // Added todoList and setTodoList as dependencies

但是,我们必须小心不要infinite loop在我们的组件中创建一个。因为setTodoList()将触发组件的重新渲染并再次useEffect()被调用。这将继续发生。

如果发生这种情况,解决方案是使用useCallback()aroundsetTodoList来防止每次都重新创建函数(我们可能还需要对代码进行一些格式化)

于 2021-01-24T11:55:23.583 回答
0

此错误是由您的 eslint 规则引起的:httpseslint.rc ://reactjs.org/docs/hooks-rules.html 您可以通过添加以下内容 来关闭您的规则:

{
  "rules": {
    "react-hooks/exhaustive-deps": "off"
  }
}
于 2021-01-24T11:56:07.133 回答