我有一个对象数组:
// 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/