使用 useState 挂钩状态更改后,React JS 代码不会重新呈现

React JS Code is not re-rending after State change using useState hook

我正在开发一个简单的数独应用程序,但我意识到我的代码在状态更改后不会重新呈现。 我已经用所有空值初始化了一个二维矩阵。然后我通过读取我的 JSON 文件来填充矩阵。在这里,当我使用 setter 函数 setValueMatrix 时,我的代码没有重新呈现。我控制台在 setter 下面的函数中记录了输出,这里显示了新的输出,但是在 return 函数中,它仍然显示 null。

所以我尝试创建另一个名为 setName 的状态变量并将其更新到 setValueMatrix 下方,然后代码重新呈现!

为什么我的代码在 setValueMatrix 之后没有重新渲染?

所附代码在 setter 函数旁边有注释。

import React, { useState, useEffect} from 'react';
import './App.css';
import jsonfile from './puzzle.json';

function App() {
  const [valueMatrix, setValueMatrix] = useState(Array.from({length: 9},()=> Array.from({length: 9}, () => null)));
  const [name, setName] = useState("0")
  useEffect(() =>{
    populateArray();
  })

  const populateArray = () => {
    //console.log("JSON file:", jsonfile.sudokugrid)
    //console.log("State Value Matrix:", valueMatrix)

    //copying the matrix into local memory
    let copymatrix = valueMatrix;
    valueMatrix.map((row, rowIndex) => (
      row.map((column, columnIndex) => (
        copymatrix[rowIndex][columnIndex] = jsonfile.sudokugrid[rowIndex][columnIndex].value
      ))
    ))
    setInitialMatrix(copymatrix);
    console.log("New Val:", valueMatrix)
  }

  const setInitialMatrix = (copymatrix) => {
    setValueMatrix(copymatrix);   //This part here!! The code isnt re-rendering after this setter!
    //setName("5214")   //But this causes a re-render!
  }


  return (
    <div className="App">
      <div>
      {
        console.log(valueMatrix[4][2])
      }
      </div>
    </div>
  )
}

不重新渲染是正常的,因为您将相同的引用传递给了 setValueMatrix。

相反,每次更改 Matrix 值时都必须生成一个新数组。

注意:数组的类型是对象。在 JavaScript 中,数组在技术上是对象;只是有特殊的行为和能力。

更改数组中元素对象的任何元素或字段不会影响您的数组对象。你应该深入更新它。

有一些方法。你可以看看here.

如果你需要一个快速的方法来清楚地看到差异,你也可以检查this