小编典典

使用 useState 编辑对象数组中的多个对象值

javascript

我有一个类似于下面的对象数组

[array1, setArray1] = useState(
        [
        {
          name: "somename",
          count: 0,
          division: "somedivision",
          cost: 1000,
        },
        {
          name: "secondname",
          count: 0,
          division: "somedivision",
          cost: 2000,
        },
      ]
)

如何单独更新列表中每个对象的成本值?

我在想像 setArray1((previous) => ({…previous, cost: newcost}))

但是我怎样才能为对象数组中的多个对象做到这一点呢?


阅读 241

收藏
2022-07-25

共1个答案

小编典典

const App = () =>{
  const [array, setArray] = React.useState([
        {
          name: "somename",
          count: 0,
          division: "somedivision",
          cost: 1000,
        },
        {
          name: "secondname",
          count: 0,
          division: "somedivision",
          cost: 2000,
        },
  ])
  const updateCosts = () => {
    let newCosts = [1002, 2006]
    setArray(previous => 
      previous.map((elem, index)=> {
        return({...elem, cost: newCosts[index]})
      })
     )
  }

  return(
    <div>
    <button onClick={()=>updateCosts()}>Update costs</button>
    { array.map(elem => <p key={elem.name}>{`Product ${elem.name} Cost ${elem.cost}`}</p>) }
    </div>
  )
}

ReactDOM.render(
    <App/>,
    document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

2022-07-25