繁体   English   中英

单元组件未在 React 中重新渲染

[英]Cell Component not re-rendering on Board in React

编辑

我能够开始让单元格重新渲染,但只有在第 106 行添加setCellsSelected之后。不知道为什么现在这样工作,反应令人困惑。

概括

目前我正在尝试在 React 中创建深度优先搜索的可视化。 搜索本身正在工作,但单元格组件没有重新渲染以显示它们已被搜索

在此处输入图像描述

它从左上角的单元格开始,检查向右或向下的单元格。 搜索到单元格后,它应该变为绿色。 我的cells阵列 state 在板级发生变化,所以我假设板会重新渲染但无济于事。 现在我只搜索(0,0)正下方的单元格作为测试。

代码

Board.js

const Cell = (props) => {

  let cellStyle; // changes based on props.value
  if (props.value === 3) cellStyle = "cell found";
  else if (props.value === 2) cellStyle = "cell searched";
  else if (props.value === 1) cellStyle = "cell selected";
  else cellStyle = "cell";

  return <div className={cellStyle} onClick={() => props.selectCell()}></div>;
};

const Board = () => {

  // 0 = not searched
  // 1 = selected
  // 2 = searched
  // 3 = selected found
  const [cells, setCells] = useState([
    new Array(10).fill(0),
    new Array(10).fill(0),
    new Array(10).fill(0),
    new Array(10).fill(0),
    new Array(10).fill(0),
    new Array(10).fill(0),
    new Array(10).fill(0),
    new Array(10).fill(0),
    new Array(10).fill(0),
    new Array(10).fill(0),
  ]); // array of cells that we will search through, based on xy coordinates
  const [start, setStart] = useState("00");

  const selectCell = (x, y) => {
    // Make sure to copy current arrays and add to it
    let copyCells = [...cells];
    copyCells[x][y] = 1;
    setCells(copyCells);
  };

  const renderCell = (x, y) => {
    return (
      <Cell
        key={`${x}${y}`}
        value={cells[x][y]}
        selectCell={() => selectCell(x, y)}
      />
    );
  };

  const renderBoard = () => {
    let board = [];
    for (let i = 0; i < cells.length; i++) {
      let row = [];
      for (let j = 0; j < cells.length; j++) {
        let cell = renderCell(i, j);
        row.push(cell);
      }
      let newRow = (
        <div className="row" key={i}>
          {row}
        </div>
      );
      board.push(newRow);
    }
    return board;
  };

  const startSearch = () => {
    // start with our current startingCell
    const startX = parseInt(start[0]);
    const startY = parseInt(start[1]);

    let copyCells = [...cells];
    const searchCell = (x, y) => {
      console.log("Coordinate:", x, y);
      if (x >= cells.length) return;
      if (y >= cells.length) return;
      let currentCell = copyCells[x][y];
      console.log(copyCells);
      if (currentCell === 1) {
        copyCells[x][y] = 3;
        console.log("Found!");
        console.log(x, y);
        return;
      } else {
        console.log("Not Found");
        copyCells[x][y] = 2;
        setTimeout(() => {
          searchCell(x + 1, y);
        }, 3000);
        setTimeout(searchCell(x, y + 1), 3000);
      }
    setCells(copyCells);
    setCellsSelected(['12']) // this works for some reason
    };
    searchCell(startX, startY);
  };

  return (
    <>
      <div style={{ margin: "25px auto", width: "fit-content" }}>
        <h3>Change search algorithm here!</h3>
        <button onClick={() => startSearch()}>Start</button>
      </div>
      <div className="board">{renderBoard()}</div>
    </>
  );
};

export default Board;

你有两个问题:

工作演示: https://codesandbox.io/s/wonderful-cartwright-qldiw

第一个问题是您在长期运行的 function 中执行 setStates。 尝试保持搜索 state 并更新位置而不是递归调用。

另一个问题是在selectCell function

您正在通过引用复制行( let copyCells = [...cells]; ),因此当您更改单元格( copyCells[x][y] = 1; )时,您也在更改原始行,因此差异将说 state 没有改变。

  const selectCell = (x, y) => {
    // Make sure to copy current arrays and add to it
    let copyCells = [...cells];
    copyCells[x][y] = 1;
    setCells(copyCells);
  };

尝试更改为let copyCells = [...cells.map(row=>[...row])];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM