简体   繁体   English

在 React 中使用 useState 更新二维数组矩阵

[英]Update a 2D array matrix with useState in React

I have the following function:我有以下功能:

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;

This works, but this is always for a 3x3 matrix.这有效,但这始终适用于 3x3 矩阵。 I have to set this dynamic, so I thought I'll set the default state with ES6 array construction like:我必须设置这个动态,所以我想我会用 ES6 数组构造设置默认状态,如:

const n = 4; // Will be set through props
const [matrix, setMatrix] = useState(Array(n).fill(Array(n).fill(null)));

But when I use this case and I update (type a number in an input field), the whole column in the matrix will get that number.但是当我使用这种情况并更新(在输入字段中输入一个数字)时,矩阵中的整列都将获得该数字。

矩阵应该只更新矩阵[0][0]

更新每行的所有第一项

Can anybody explain this?有人可以解释一下吗?

When I use this piece of code:当我使用这段代码时:

const [matrix, setMatrix] = useState(
    Array.from({ length: 3 }, v => Array.from({ length: 3 }, v => null))
  );

it works again.它再次起作用。

Array(n).fill(null) is evaluated once and it populates the entire array with the same reference values and hence when you update a single column, all rows are updated. Array(n).fill(null)被评估一次,它用相同的引用值填充整个数组,因此当您更新单个列时,所有行都会更新。

To solve this issue, you can use Array.from to create a 2D matrix like Array.from({length: n},()=> Array.from({length: n}, () => 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.

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