如何使用 spreador 将带有键的对象推送到新数组

how to push an object with key using spreador to a new array

我想向新数组中添加一个元素,但错误通知让我感到困惑而不是 work.If 用户单击颜色选择器input 并输入 title 并单击 Add Color按钮,一张新卡将显示在 case.This 是我的期望。

import ColorCards from "./ColorCards";
import React, { useState } from "react";
import data from "./initialState.json";
import { v4 as uuidv4 } from "uuid";

export default function CardsafterEvents({ title, color }) {
  const [colors, setColors] = useState(data.colors);
  const onRemove = (id) => {
    const newcolors = colors.filter((color) => color.id !== id);

    setColors(newcolors);
  };
  const AddColor = (id, title, color, timestamp) => {
    const newcolors = [
      ...colors,
      {
        id: uuidv4(),
        title: title,
        color: color,
        timestamp: new Date()
      }
    ];
    setColors(newcolors);
  };

  return (
    <>
      <ColorCards
        dataColors={colors}
        handleDelete={onRemove}
        title={title}
        color={color}
        HandleColor={AddColor}
      />
    </>
  );
}

完整项目link:https://codesandbox.io/s/material-demo-forked-62eh0?file=/CardsafterEvents.js:0-839

不确定您的问题,但是,如果 timestamp 转换为如下字符串,则会添加一张新卡片:

const newcolors = [
  ...colors,
  {
    id: uuidv4(),
    title: title,
    color: color,
    timestamp: new Date().toString()
  }
];

你的项目有一些问题,但我得到了你要求的功能。

查看更新后的 Codesandbox。

问题在于函数 HandleColor 以及您如何处理状态。

我会突出显示我所做的更改

//Added to ColorCards.js
const [title, setTitle] = useState("");
const [color, setColor] = useState("");

const handleColorChange = (e) => {
  HandleColor(title, color, new Date().toString());
};

//Slight modifications here
<input
    type="text"
    placeholder="color title "
    style={{ width: "1500px", height: "20px", fontSize: "20" }}
    value={title}
    onChange={(e) => setTitle(e.target.value)}
/>
<input
    type="color"
    value={color}
    onChange={(e) => setColor(e.target.value)}
    style={{ width: "50px", height: "30px" }}
/>
<Button
    variant="contained"
    color="inherit"
    style={{ float: "right", width: "90px", height: "30px" }}
    onClick={handleColorChange}
>

//Changes in CardsafterEvents.js
const AddColor = (title, color, timestamp) => {
    const newcolors = [
      ...colors,
      {
        id: uuidv4(),
        title: title,
        color: color,
        timestamp: timestamp
      }
    ];
    setColors(newcolors);
};