使用 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>
)
}
我正在开发一个简单的数独应用程序,但我意识到我的代码在状态更改后不会重新呈现。 我已经用所有空值初始化了一个二维矩阵。然后我通过读取我的 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>
)
}