简体   繁体   English

如何在 React 中的 object 内的数组中添加 object?

[英]How to add an object inside an array inside an object in React?

I'm trying to insert a task with multiple fields like title, text, and tag only in the 'To Do' category.我正在尝试仅在“待办事项”类别中插入具有多个字段(如标题、文本和标签)的任务。 It would be an object inside an array, inside an object.它将是一个 object 在一个数组内,在一个 object 内。 The way I'm implementing it is totally wrong, and it's generating a chain of objects inside another object.我实现它的方式是完全错误的,它在另一个 object 中生成了一系列对象。 How could I be performing so that the data looks the same as in the Table?我怎样才能使数据看起来与表中的相同?

This is the way I need the data to be saved:这是我需要保存数据的方式:

const Table = [
  {
    id: uuidv4(),
    title: "To do",
    tasks: [
      {
        id: uuidv4(),
        title: "Learn JavaScript",
        text: "lorem ipsum",
        tag: "tag1",
      },
      {
        id: uuidv4(),
        title: "Learn Git",
        text: "lorem ipsum",
        tag: "tag2",
      },
    ],
  },
  {
    id: uuidv4(),
    title: "Doing",
    tasks: [
      {
        id: uuidv4(),
        title: "Learn CSS",
        text: "lorem ipsum",
        tag: "tag1",
      },
    ],
  },
  {
    id: uuidv4(),
    title: "Done",
    tasks: [
      {
        id: uuidv4(),
        title: "Learn HTML",
        text: "lorem ipsum",
        tag: "tag1",
      },
    ],
  },
];

This is the code I made这是我制作的代码

  import React, { useState } from "react";
import Input from "./Input";
import "./App.css";

const App = () => {
  const [tasks, setTasks] = useState([]);
  function addTask(task) {
    const newTask = { ...task };
    newTask[0] = {
      ...tasks[0],
      arrayTasks: task,
    };
    setTasks([...tasks, newTask]);
  }
  return (
    <div>
      <Input onAdd={addTask} />
    </div>
  );
};

export default App;

and this one:和这个:

import { useState } from "react";

const Input = ({ onAdd }) => {
  const [title, setTitle] = useState("");
  const [text, setText] = useState("");
  const [tag, setTag] = useState("");
  const [status, setStatus] = useState("ToDo");

  const onSubmit = (e) => {
    e.preventDefault();

    if (!text || !title) {
      alert("Please enter a task with a title");
      return;
    }
    const number = Math.floor(Math.random() * 10000) + 1;
    const id = "" + number;
    onAdd({ title, text, tag, status, id });
    setTitle("");
    setText("");
    setTag("");
    setStatus("ToDo");
  };

  return (
    <div>
      <input
        type="text"
        placeholder="Add Title"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
      />
      <input
        type="text"
        placeholder="Add Task"
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
      <input
        type="text"
        placeholder="Insert you tag"
        value={tag}
        onChange={(e) => setTag(e.target.value)}
      />
      <button type="submit" onClick={onSubmit}>
        Save Task
      </button>
    </div>
  );
};

export default Input;

This is the output这是 output

if you expect your task state to be like the table array.如果您希望您的任务 state 像表格数组一样。 so i think you need first to refer to which item in the array to update.所以我认为您需要首先参考要更新的数组中的哪个项目。 so i suggest you need to pass an extra param to the function 'id of the target item or row' .所以我建议您需要将一个额外的参数传递给 function 'id of the target item or row'

and so, you can try something like this.所以,你可以尝试这样的事情。

// the second param is the id of target row or item which contain the tasks obj.

function addTask(task, id) {
    const tasksCopy = [...tasks]; // should be a copy of table variable

    const targetObjIndex = tasksCopy.findIndex((tbl) => tbl.id === id);
    const resetOfTheArray = tasksCopy.filter((tbl) => tbl.id !== id);

    let targetItem = tasksCopy[targetObjIndex];

    targetItem = { ...targetItem, tasks: [...targetItem.tasks, task] };

  return [...resetOfTheArray, targetItem];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM