【问题标题】:React: How to update 2d array in loop by one click?React:如何一键更新循环中的二维数组?
【发布时间】:2020-01-28 02:39:05
【问题描述】:

我是 React 新手,想一键更新循环中的二维数组。
我想要的实现如下所示

  1. 循环二维数组
  2. 循环中的每个元素,将该元素着色为黄色(表示需要渲染)
  3. 每次着色都必须延迟此过程

但是,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


    【解决方案1】:

    您正在做的是 - 立即运行 for 循环并将所有单元格的板值更改为黄色。下一次(以及每次)调用 setBoard 时,板子已经是黄色的了。

    您可能想要更改的是 - 更新 setTimeout 中的每个电路板单元格。

    您可以采取的一种方法是:

      function updateBoard(board, row, col) {
        if (col >= board[row].length) {
          row++;
          col = 0;
        }
        board[row][col] = "yellow";
        setBoard(board);
    
        if(row >= board.length-1 && col >= board[0].length-1) {
          return;
        }
        setTimeout(() => {
          updateBoard(board, row, ++col);
        }, 1000);
      }
    

    【讨论】:

      猜你喜欢
      • 2019-02-04
      • 2018-07-19
      • 1970-01-01
      • 2019-06-02
      • 2011-06-03
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      • 2016-06-25
      相关资源
      最近更新 更多