最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to update with React Hooks specific value of an array inside an object? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Apr 15, 2019 at 15:05 Tholle 113k22 gold badges208 silver badges197 bronze badges asked Apr 15, 2019 at 15:00 Besart MarkuBesart Marku 5431 gold badge7 silver badges14 bronze badges 3
  • you cannot update a specific value, because that is a mutation, instead you should create a new brand array that reflects the update – AngelSalazar Commented Apr 15, 2019 at 15:02
  • What do you mean by making the second value equal to 0? You want to set the second item of the nested array to 0 for all items in rowEdit? – nanobar Commented Apr 15, 2019 at 15:02
  • @Dominic, for example the new array should be [1,0,1,1,1] – Besart Marku Commented Apr 15, 2019 at 15:04
Add a ment  | 

2 Answers 2

Reset to default 4

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./react@16/umd/react.development.js"></script>
<script src="https://unpkg./react-dom@16/umd/react-dom.development.js"></script>

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

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),
}), {}));
发布评论

评论列表(0)

  1. 暂无评论