簡體   English   中英

在 React 中使用 useState 更新二維數組矩陣

[英]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)));

但是當我使用這種情況並更新(在輸入字段中輸入一個數字)時,矩陣中的整列都將獲得該數字。

矩陣應該只更新矩陣[0][0]

更新每行的所有第一項

有人可以解釋一下嗎?

當我使用這段代碼時:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM