英文:
Fill array with key-value values
问题
我正在尝试用对象填充一个数组。如果我执行 setState,新条目不会被添加,但数组的结构会被扩展。例如:初始条目(0),新条目(0->0),另一个条目(0->0->0)。然而,我希望为每个条目添加一个连续编号。
const [entrys, setEntrys] = useState([{ date: "", entry: "" }]);
-> 点击按钮
setEntrys((prev) => [{ ...prev, date: clickedDay, entry: hinweis }]);
英文:
I'm trying to fill an array with objects. If I execute setState, the new entry is not added but the structure of the array is extended. Example: Initial entry (0), new entry (0->0), another entry (0->0->0). I would like however for each entry a running numbering
const [entrys, setEntrys] = useState([{ date: "", entry: "" }]);
->click on button
setEntrys((prev) => [{ ...prev, date: clickedDay, entry: hinweis }]);
答案1
得分: 1
你遇到的问题是在传递的对象内部使用展开运算符(spread operator)包含了先前的状态,比如 "prev"。
你想要做的是将你要保存到状态中的新对象包含进去,然后将先前的状态,比如 "prev",作为数组中的一个单独元素包含在里面,就像下面这样。
我也为你提供了一个 codesandbox 链接 https://codesandbox.io/s/romantic-solomon-l566yy?file=/src/App.js。
英文:
The problem you're having is that you have included the previous state, e.g. "prev" with the spread operator inside the object you are passing.
What you want to do is include the new object you are saving to state AND then include previous state, e.g. "prev" as a separate element in the array - like below.
I've included a codesandbox for you too https://codesandbox.io/s/romantic-solomon-l566yy?file=/src/App.js.
import "./styles.css";
import React, { useState } from "react";
const App = () => {
const [entries, setEntries] = useState([
{
date: "",
text: ""
}
]);
const handleClick = () => {
setEntries((prevEntry) => {
return [...prevEntry, { date: "date", text: "test" }];
});
};
return (
<div>
<button onClick={handleClick}>Click me!</button>
</div>
);
};
export default App;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论