[英]Update 2d array using React and hooks useState and useEffect
[英]Update a 2D array matrix with useState in React
我有以下功能:
import React, { useState } from "react";
const Sheet = () => {
const [matrix, setMatrix] = useState([
[null, null, null],
[null, null, null],
[null, null, null]
]);
const handleChange = (row, column, event) => {
let copy = [...matrix];
copy[row][column] = +event.target.value;
setMatrix(copy);
console.log(matrix);
};
return (
<div className="sheet">
<table>
<tbody>
{matrix.map((row, rowIndex) => (
<tr key={rowIndex}>
{row.map((column, columnIndex) => (
<td key={columnIndex}>
<input
type="number"
onChange={e => handleChange(rowIndex, columnIndex, e)}
/>
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
);
};
export default Sheet;
这有效,但这始终适用于 3x3 矩阵。 我必须设置这个动态,所以我想我会用 ES6 数组构造设置默认状态,如:
const n = 4; // Will be set through props
const [matrix, setMatrix] = useState(Array(n).fill(Array(n).fill(null)));
但是当我使用这种情况并更新(在输入字段中输入一个数字)时,矩阵中的整列都将获得该数字。
有人可以解释一下吗?
当我使用这段代码时:
const [matrix, setMatrix] = useState(
Array.from({ length: 3 }, v => Array.from({ length: 3 }, v => null))
);
它再次起作用。
Array(n).fill(null)
被评估一次,它用相同的引用值填充整个数组,因此当您更新单个列时,所有行都会更新。
为了解决这个问题,你可以使用 Array.from 创建一个二维矩阵,如Array.from({length: n},()=> Array.from({length: n}, () => null))
const { useState } = React; const n = 4; const Sheet = () => { const [matrix, setMatrix] = useState(Array.from({length: n},()=> Array.from({length: n}, () => null))); const handleChange = (row, column, event) => { let copy = [...matrix]; copy[row][column] = +event.target.value; setMatrix(copy); console.log(matrix); }; return ( <div className="sheet"> <table> <tbody> {matrix.map((row, rowIndex) => ( <tr key={rowIndex}> {row.map((column, columnIndex) => ( <td key={columnIndex}> <input type="number" onChange={e => handleChange(rowIndex, columnIndex, e)} /> </td> ))} </tr> ))} </tbody> </table> </div> ); }; ReactDOM.render(<Sheet />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script> <div id="app" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.