代码之家  ›  专栏  ›  技术社区  ›  Ilkhom Tashkulov

如何将数组添加到数据中的特定对象?

  •  0
  • Ilkhom Tashkulov  · 技术社区  · 4 年前

    enter image description here . 但是,我需要它在一个物体里面。

    // This is my data
    const [list, setList] = useState({
            home: {
              title: "Home",
              color: "#5786ff",
              icon: <MdContentPaste />,
              tasks: [
                {
                  note: "Play Basketball",
                  time: "21:00",
                },
              ],
            },
            work: {
              title: "Work",
              color: "#ffc93c",
              icon: <MdMailOutline />,
              tasks: [
                { note: "Write Essay", time: "2:00" },
              ],
            },
          });
    
    // Here I am trying to add the notes to my tasks
    const [noteInput, setNoteInput] = useState("");
    const [noteTime, setNoteTime] = useState("");
    const handleSubmit = () => {
        setList({
          ...list,
          tasks: [...list[listName].tasks, { note: noteInput, time: noteTime }],
        });
      };
    
    // Explanation
    (...list[listName].tasks) - takes the parent object's tasks
    
    1 回复  |  直到 4 年前
        1
  •  0
  •   Ilkhom Tashkulov    4 年前

    这个 listName

    setList({
          ...list,
          [listName]: {
            ...list[listName],
            tasks: [...list[listName].tasks, { note: noteInput, time: noteTime }],
          },
        });