更新状态,而不将其设置为 useEffect 中的依赖项?详尽的 lint 规则

Updating a state, without setting it as a dependency in useEffect? exhaustive-deps lint rule

我有一个页面状态,当它更新时我想将新项目添加到另一个状态,在本例中是一个列表状态。

在下面的示例中,我在 useEffect 中使用了 page 作为依赖项,但不能使用 list,因为它会导致无限循环。

  const [list, setList] = useState([1, 2, 3, 4]);
  const [page, setPage] = useState(1);

  useEffect(() => {
    const newList = ["a", "b", "c", "d"];
    setList(list.concat(newList));
  }, [page]);

虽然这有效,但它会触发 exhaustive-deps lint 规则。我阅读了该规则并了解到让依赖项数组没有所有使用的值是个坏主意,我真的不想只禁用此规则。

在这种情况下,更新页面时更新列表的正确方法是什么?

您应该使用 setList

的回调版本
  const [list, setList] = useState([1, 2, 3, 4]);
  const [page, setPage] = useState(1);

  useEffect(() => {
    const newList = ["a", "b", "c", "d"];
    setList(currentList => currentList.concat(newList));
  }, [page]);