用键值对填充数组

huangapple go评论69阅读模式
英文:

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;

huangapple
  • 本文由 发表于 2023年2月6日 17:59:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75359796.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定