【问题标题】:Update value in nested object in React useState在 React useState 中更新嵌套对象中的值
【发布时间】:2022-09-27 17:14:25
【问题描述】:

我有这个useState:

const [data, setData] = useState([
  {
    id: 1,
    options: [{ id: 1, amount: 0 }, { id: 2, amount: 0 }]
  },
  {
    id: 2,
    options: [{ id: 1, amount: 0 }, { id: 2, amount: 0 }]
  }
]);

所以我需要一个函数来更新项目 X 中的选项 X。

像这样:

const increase = (itemId, optionId) => {
   //setData(...) 
}

我试着做这样的事情:

const increase = (itemId, optionId) => {
    const copy = [...data];

    const dataItem = copy.find((item) => item.id === itemId);
    const option = dataItem.options.find((item) => item.id === optionId);

    option.amount = option.amount + 1;
    setData(copy);
}

但它增加了两个...

  • 为什么不在最后一行 increase 上使用 setData(copy)
  • 是的,这是实际的代码对不起,我会更新
  • 好吧,没关系,它现在可以工作了,在它增加了两个之前

标签: javascript reactjs


【解决方案1】:

尝试这个

const handleClick = (itemId, optionId) => {
    setData((prevArr) => {
      return prevArr.map((item) => {
        if (item.id !== itemId) return item;

        const updOptions = item.options.map((option) =>
          option.id === optionId
            ? {
                ...option,
                amount: option.amount + 1
              }
            : option
        );

        return {
          ...item,
          options: updOptions
        };
      });
    });
  };

UPD:更新示例

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-24
    • 2021-02-28
    • 2019-11-02
    • 2019-02-26
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    • 2020-11-13
    相关资源
    最近更新 更多