如何使用 onClick 更改对象数组中的值?

How to change values in array of objects with an onClick?

我正在使用 React 并尝试在按下按钮时编辑对象。目前,我在页面上呈现了 2 个显示其正确值的按钮,但是当按下按钮时我得到“buttonUpgrades.map 不是一个函数”。 changeButtonData 函数可以记录正确的数据,但我似乎无法对数据进行任何更改。

根据我的理解,这是发送错误的原因是 buttonUpgrades 是一个对象,但我不知道如何解决这个问题。

import React, { useState } from "react";
const UpgradeButton = () => {
    const [buttonUpgrades, updateButtonUpgrades] = useState([
    {
      id:0,
      name: "Upgrade one",
      cost: 5,
      amount: 0,
      damage: 1,
      damageGrowth: 1.1,
    },
    {
      id:1,
      name: "Upgrade two",
      cost: 6,
      amount: 0,
      damage: 2,
      damageGrowth: 1.2,
    },
  ]);

  const changeButtonData = (data) => {
    let {name,cost,damage} = data;
    updateButtonUpgrades(...buttonUpgrades, name="new name") // this wont let me change the value that has been assigned
    console.log(name) // this logs the name assigned to the button 
  }

  return(  
    buttonUpgrades.map((upgrade)=>
    <button key={upgrade.id}onClick={()=>changeButtonData(upgrade)}>
      <h1>Cost:{upgrade.name}</h1>
      <h1>Cost:{upgrade.cost}</h1>
      <h1>Damage:{upgrade.damage}</h1>
    </button>
    )
  )
}
export default UpgradeButton;

编辑:万一有人遇到这个问题的解决方案:

  const changeButtonData  = (data)=>{
    const {id,name,cost,amount,damage,damageGrowth} = data;
    updateButtonUpgrades(buttonUpgrades.map(buttonProps=>(buttonProps.id===id ? {...buttonProps,damage:damage * damageGrowth}:buttonProps)))
  }

我建议您重写您的 onClick 回调函数:首先创建具有所需属性的新对象,将它们分组到一个数组中,然后使用这个新数组更新反应状态。

编辑:jharris711 给出了这个概念的干净实现,干得好!

首先,您的 updateButtonUpgrades 设置不正确。

updateButtonUpgrades(...buttonUpgrades, name="new name")

试图在组件的 return 中映射按钮升级,但您拥有它 spread with the ... syntax in your updateButtonUpgrades function call, so all you're doing is passing the items in the array to the function 而不是向数组添加项目。 这就是您从 得到 buttonUpgrades.map 不是函数错误的地方。要解决这个问题,应该这样设置:

updateButtonUpgrades([...buttonUpgrades, (name = "new name")])

使用数组的扩展语法 INSIDE。但是现在,您所做的只是向数组添加“新名称”,如下所示:

[
  {id: 0, name: "Upgrade one", cost: 5, amount: 0…},
  {id: 1, name: "Upgrade two", cost: 6, amount: 0…},
  "new name"
]

从这里开始:

  • 如果你想添加一个对象,你会这样做:
updateButtonUpgrades([...buttonUpgrades, { name: "new name", cost, damage }]);
  • 如果您想用新值替换一个值,您应该查看