How to update with React Hooks specific value of an array inside an object?

筅森魡賤 提交于 2021-02-09 00:39:57

问题


I have an object which i want to update it using React Hooks

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

I loop through the array with .map, so i have the index for each element. How can i make the second value equal to 0?


回答1:


You can return 0 if the map index is equal to 1, or return the current element otherwise.

Example

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>



回答2:


It's unclear if you want to do this for all keys in the object, but I'm going to assume you do:

setRowEdit(rows => Object.entries(rows).reduce((obj, [rowId, row]) => ({
  ...obj,
  [rowId]: row.map((col, i) => i === 1 ? 0 : col),
}), {}));

Otherwise:

setRowEdit(rows => ({
  ...rows,
  '1x0': rows['1x0'].map((col, i) => i === 1 ? 0 : col),
}), {}));


来源:https://stackoverflow.com/questions/55692004/how-to-update-with-react-hooks-specific-value-of-an-array-inside-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!