我有一个我想使用React Hooks更新的对象

const [rowEdit, setRowEdit] = useState({ rowEdit: { "1x0": [1, 1, 1, 1, 1] } });

我用.map遍历数组,所以我有每个元素的索引。如何使第二个值等于0?

最佳答案

如果0索引等于map,则可以返回1,否则返回当前元素。

示例

const { useState } = React;

function App() {
  const [rowEdit, setRowEdit] = useState({
    rowEdit: { "1x0": [1, 1, 1, 1, 1] }
  });

  function onClick() {
    setRowEdit(prevState => ({
      ...prevState,
      rowEdit: {
        ...prevState.rowEdit,
        "1x0": prevState.rowEdit["1x0"].map((row, index) =>
          index === 1 ? 0 : row
        )
      }
    }));
  }

  return (
    <div>
      <button onClick={onClick}>update row</button>
      <div>{JSON.stringify(rowEdit)}</div>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

10-07 21:11