删除状态映射中的特定字段总是删除该字段的最后一个元素



我在函数组件中用useState定义了一个状态,如下所示:

const [appointmentList, setAppointmentList] = useState([]);

这个州代表了一个表格列表,我可以像这样添加我想添加的数量:

const addAppointment = useCallback(() => {
setAppointmentList([...appointmentList, {id: uuid()}]);
}, [appointmentList]);

但我遇到了一个问题,当它来删除预约。要做到这一点,我使用这个useCallback:

const removeAppointment = useCallback((i) => {
let newAppointmentList = [...appointmentList];
newAppointmentList.splice(i, 1);
setAppointmentList(newAppointmentList)
}, [appointmentList]);

在该状态下删除正确的约会效果很好,但在我的应用程序视图中总是删除最后一个约会。

举个例子,我有两个表格,里面都是数值。我点击删除了第一个表格,在我的状态下,我现在只在appointmentList状态中获得了第二个表格的值,但在我看来,最后一个表格已经被删除了,所以我仍然获得了带有他的值的第一个表格。。。

我认为问题可能来自这样一个事实,即我的功能只删除了该州的正确约会,然后地图意识到约会列表减少了,然后地图显示了最近的约会,而不是选择删除的约会。

我的表格如下:

return(
<div>
{appointmentList.map((appointment, index) => (
<Row key={`${index}`} id={index}>
<Col>
<Field
name={`appointments[${index}].title`}
id="title"
component={InputTextField}
value={appointment.title || ""}
onChange={e => handleChange(index, e)}
/>
<Field
manyOther field
/>
<Button
theme={BUTTON_THEMES.SECONDARY}
size={BUTTON_SIZES.SMALL}
onClick={() => removeAppointment(index)}
>
</Col>
</Row>
))}
<div>
<Button
theme={BUTTON_THEMES.SECONDARY}
size={BUTTON_SIZES.SMALL}
onClick={addAppointment}
>
</div>
</div>

那么我该如何删除正确的表单呢?

谢谢你的帮助

这是一个工作演示。你们的代码相似吗?因为我的在工作。

Codesandbox

import { useState } from "react";
import "./styles.css";
export default function App() {
const [appointmentList, setAppointmentList] = useState([1, 2, 3, 4, 5]);
const addAppointment = () => {
setAppointmentList([...appointmentList, { id: uuid() }]);
};
const removeAppointment = (i) => {
let newAppointmentList = [...appointmentList];
newAppointmentList.splice(i, 1);
setAppointmentList(newAppointmentList);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<div style={{ display: "flex", flexDirection: "column" }}>
{appointmentList.map((item, index) => {
return <div key={item.id}> {item.id} <button onClick={() => removeAppointment(index)}>delete</button></div>;
})}
</div>
<button onClick={addAppointment} >Add</button>
</div>
);
}

最新更新