【发布时间】:2020-01-28 02:39:05
【问题描述】:
我是 React 新手,想一键更新循环中的二维数组。
我想要的实现如下所示
- 循环二维数组
- 循环中的每个元素,将该元素着色为黄色(表示需要渲染)
- 每次着色都必须延迟此过程
但是,React 的 setState 是异步的并且是一次批处理的,所以我使用了 setTimeout 但它不起作用。
我怎么解决这个问题。这是我的代码和代码框链接
import React, { useState } from "react";
export default function App() {
const [board, setBoard] = useState(Array(10).fill(Array(10).fill(null)));
const onClick = () => {
const copy = JSON.parse(JSON.stringify(board));
board.forEach((row, ridx) => {
row.forEach((col, cidx) => {
copy[ridx][cidx] = "yellow";
setTimeout(setBoard(copy), 1000 * (ridx + cidx));
});
});
};
return (
<>
{board.map((row, ridx) => (
<div key={ridx} style={{ display: "flex" }}>
{row.map((col, cidx) => {
const bgColor = board[ridx][cidx];
return (
<div
style={{
width: "64px",
height: "64px",
border: "1px solid black",
backgroundColor: bgColor
}}
/>
);
})}
<br />
</div>
))}
<button onClick={onClick}>START</button>
</>
);
}
【问题讨论】:
标签: reactjs settimeout setstate