从列表中删除项目时出现问题



我正在尝试创建一个待办事项列表,删除项目并将其状态更改为已完成。当我单击某个项目的复选框时,它只删除第一个项目,当我试图将该项目的状态更改为已完成时,它表示该项目不存在。因此,我假设这是我传递给remove函数的项的索引的问题。如有任何帮助,我们将不胜感激。谢谢。

这些是todo对象:

const [todos, setTodos] = useState([
{
text: "Learn about React",
isCompleted: true
},
{
text: "Meet friend for lunch",
isCompleted: false
},
{
text: "Wash Dishes",
isCompleted: false
}
]);

这就是我删除项目时的名称

const removeTodo = index => {
const checkTodos = [...todos];         //The list is copied and isCompleted is changed to true
checkTodos[index].isCompleted = true;  //This line results in: 
setTodos(checkTodos);                  //Cannot set property 'isCompleted' of undefined
const newTodos = [...todos];           //Here is where I remove from the list
newTodos.splice(index, 1);             //I remove the specific index but it deletes only the first 
setTodos(newTodos);                    //item no matter where I click
};

这就是我如何调用删除函数

<div style = {{paddingTop: 40}}>
<List>
{todos.map((value) => {
return(
<ListItem>
<ListItemIcon>
<Checkbox
edge="start"
checked={value.isCompleted}
onChange={removeTodo}         //Remove function is called here 
tabIndex={-1}
disableRipple
/>
</ListItemIcon>
<ListItemText disableTypography style={{fontFamily: 'Work Sans', fontSize: 35}} primary={value.text}/>
</ListItem>
);
})}
</List>
</div>

在react中,如果您使用Map,您应该给您的孩子一个密钥,这样它就可以唯一地识别所有密钥。然后使用索引调用removeTodo以正确删除它。

<div style = {{paddingTop: 40}}>
<List>
{todos.map((value, index) => {
return(
<ListItem key={value}>
<ListItemIcon>
<Checkbox
edge="start"
checked={value.isCompleted}
onChange={() => removeTodo(index)}          
tabIndex={-1}
disableRipple
/>
</ListItemIcon>
<ListItemText disableTypography style={{fontFamily: 'Work Sans', fontSize: 35}} primary={value.text}/>
</ListItem>
);
})}
</List>
</div>

最新更新