你好,我正在try 根据我的数据创建一个数组,我使用了MongoDB,实际上是试图将_id添加到一个数组中.如果_id已经存在,那么它不会添加,我的意思是它不会重复,因为它是一个动态数据列表,我会循环,但当我单击添加数据时,它总是只为一个元素提供一个新的数组,而不是添加新的元素.我已经try 了很多方法,希望任何人都能帮忙.
Data:个
[
{
_id: ObjectId("64d28f3abdc16189260a5521"),
blood: "A+",
birth: "2023-08-05",
role: "student",
},
{
_id: ObjectId("64d2edb9d0f86e45a48611b5"),
blood: "B+",
birth: "2013-08-05",
role: "student",
},
{
_id: ObjectId("64d2fd40d0f86e45a48611b8"),
blood: "A+",
birth: "2023-08-05",
role: "student",
},
{
_id: ObjectId("64d54434a2d26fwdsb83d12ab"),
blood: "AB+",
birth: "2013-06-05",
role: "student",
},
{
_id: ObjectId("64d48526b43hga0b83d12ab"),
blood: "A+",
birth: "2023-08-05",
role: "student",
},
{
_id: ObjectId("64d48526bd26fwdsb23sa12ab"),
blood: "B+",
birth: "2013-08-05",
role: "student",
},
{
_id: ObjectId("64d48343bd26faa0b83d12ab"),
blood: "A+",
birth: "2023-08-05",
role: "student",
},
{
_id: ObjectId("64d54434a2d26fwdsb83d12ab"),
blood: "AB+",
birth: "2013-06-05",
role: "student",
},
];
Code:个
import React, { useState } from "react";
import { Col, Container, Row } from "react-bootstrap";
import "./ArrayManipulationComponent.css"; // Import your CSS file
const StudentGrid = ({ student }) => {
const [elements, setElements] = useState([]);
const { name, birth, _id } = student;
const handleButtonClick = (_id) => {
if (elements.includes(_id)) {
const updatedElements = elements.filter(id => id !== _id);
setElements(updatedElements);
} else {
setElements([...elements, _id]);
}
};
console.log(elements);
return (
<div>
<Container>
<Row>
<Col md={12}>
<div>
<p>
<button
className={
elements.includes(_id) ? "active-button" : "action-button"
}
onClick={() => handleButtonClick(_id)}
>
Button {_id}
</button>
</p>
</div>
</Col>
</Row>
</Container>
</div>
);
};
export default StudentGrid;