javascript - 如何使用 useState Hook 更新对象的状态并保留现有元素?

标签 javascript reactjs react-hooks use-state

我有一个对象数组:

// seedColors.js

export default [
  {
    paletteName: "Material UI Colors",
    colors: [
      { name: "red", color: "#F44336" },
      { name: "pink", color: "#E91E63" },
    ]
  },
  {
    paletteName: "Flat UI Colors v1",
    colors: [
      { name: "Turquoise", color: "#1abc9c" },
      { name: "Emerald", color: "#2ecc71" },
    ]
  }
]

在我的 app.js 文件中,我正在创建一个新的对象数组,如何使用 useState Hook 将新对象附加到现有对象?

// app.js

import seedColors from "./seedColors";

function App() {
  const [palettes, setPalettes] = useState({ palettes: seedColors });

  const savePalette = (newPalette) => {
    // newPalette = { paletteName: "New Test Palette", colors: [{ color: "blue", name: "blue" }] };
    setPalettes({ ...palettes, palettes: newPalettes });
  };

这不会更新原始对象状态,而是会导致应用程序崩溃

我希望状态更新为:

[
  {
    paletteName: "Material UI Colors",
    colors: [
      { name: "red", color: "#F44336" },
      { name: "pink", color: "#E91E63" },
    ]
  },
  {
    paletteName: "Flat UI Colors v1",
    colors: [
      { name: "Turquoise", color: "#1abc9c" },
      { name: "Emerald", color: "#2ecc71" },
    ]
  },
  { 
    paletteName: "New Test Palette", 
    colors: [
      { color: "blue", name: "blue" },
    ] 
  },
]

最佳答案

您的应用程序可能会“崩溃”,因为您有一个拼写错误:

 setPalettes({ ...palettes, palettes: newPalettes });
 //                                             ^

您没有名为 newPalettes 的变量。但即使你解决了这个问题,也不会产生你想要的结果。

您将状态设置为具有单个属性的对象是否有原因?如果没有,只需直接分配数组(根据您对状态的描述,这似乎是您想要的):

const [palettes, setPalettes] = useState(seedColors);

然后您可以使用以下命令更新数组

setPalettes([...palettes, newPalette]);

如果您需要该对象,那么它将是:

setPalettes({...palettes, palettes: [...palettes.palettes, newPalette]});

关于javascript - 如何使用 useState Hook 更新对象的状态并保留现有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65042910/

相关文章:

javascript - 在 React 中输入范围内的数字

php - 如何通过终端或其他方式将参数传递给 JavaScriptCore/Console?

javascript - chrome.extension.getBackgroundPage() 不适用于 manifest_version : 3

reactjs - 我可以为 CSS 网格布局组件设置动画吗?

reactjs - 在 ReactJs 中使用鼠标事件在 Canvas 上绘制直线

vue.js - Vue.js 中是否有相当于 React 的 useId hook 的东西?

reactjs - 如何使用 swr 编写测试

javascript - Youtube V3 channel 搜索有结果但未显示项目

javascript - 将添加到文本框中的文本保存在 DOM 中

javascript - 窗口滚动事件已停止在整个域的所有实现上触发