为什么在 setTimeout 中更改 State 会导致无限循环

Eмα*_*мαd 5 reactjs

我有一个功能组件,我想更改 a 内的 State setTimeout,但我不知道为什么它会导致组件处于无限循环中!

这是我的功能组件

import { useState } from "react";

function Card() {
  const [booksState, setBooks] = useState({
    books: [
      { name: "Harry", id: 1 },
      { name: "Potter", id: 2 },
      { name: "John", id: 3 },
    ],
  });

  console.log("test");

  setTimeout(() => {
    let newBooks = [
      { name: "test1", id: 4 },
      { name: "test2", id: 5 },
      { name: "test3", id: 6 },
    ];

    setBooks({
      books: [...booksState.books, ...newBooks],
    });
  }, 2000);

  return <div>TEST</div>;
}

export default Card;

Run Code Online (Sandbox Code Playgroud)

控制台日志

在此输入图像描述

JBa*_*zuk 2

每次组件渲染时都会运行设置超时。这意味着每次状态改变时,它都会启动一个新的计时器。假设您只想在组件首次呈现时运行计时器,则应按useEffect如下方式使用挂钩:

import { useState } from "react";

function Card() {
  const [booksState, setBooks] = useState({
    books: [
      { name: "Harry", id: 1 },
      { name: "Potter", id: 2 },
      { name: "John", id: 3 },
    ],
  });

  console.log("test");

  useEffect(() => {
    setTimeout(() => {
      let newBooks = [
        { name: "test1", id: 4 },
        { name: "test2", id: 5 },
        { name: "test3", id: 6 },
      ];

      setBooks({
        books: [...booksState.books, ...newBooks],
      });
    }, 2000)
  }, []);

  return <div>TEST</div>;
}

export default Card;
Run Code Online (Sandbox Code Playgroud)