gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:26:47 25 4
gpt4 key购买 nike

我有一个功能组件,我想在setTimeout中改变状态,但我不知道为什么它会导致组件陷入死循环!

Here is my Functional Component:

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;

The console log:

enter image description here

最佳答案

Set Timeout 在每次组件渲染时运行。这意味着每次状态改变时,它都会启动一个新的计时器。假设您只想在组件首次呈现时运行计时器,您应该使用 useEffect Hook ,如下所示:

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;

关于reactjs - 为什么在 setTimeout 中更改 State 会导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71649336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com