我如何在React中从数组中删除一个项目?我尝试了几个方法,但都没有成功。只是想制作一个基本的待办事项应用程序。我更新了我的帖子,以提供渲染方法来展示deleteTodo的去向。我还更新了我的deleteTodo,使用了我从这篇文章中得到的答案。它有点起作用,唯一的问题是它删除了待办列表中的所有项目,而不仅仅是单个项目。
class App extends Component {
state = {
inputValue: "",
todos: [{
value: "walk the dog",
done: false
},
{
value: "do the dishes",
done: false
}
]
}
addTodo = (e) => {
this.setState({
inputValue: e.target.value
});
}
handleSubmit = (e) => {
e.preventDefault();
// console.log('clicked')
const newTodo = {
value: this.state.inputValue,
done: false
}
const todos = this.state.todos;
todos.push(newTodo);
this.setState({
todos,
inputValue: ''
})
}
deleteTodo = (value) => {
// Take copy of current todos
const todos = [this.state.todos];
const filteredTodos = todos.filter((item) => item.value !== value);
this.setState({
todos: filteredTodos
})
}
render() {
return (
<div className="App">
<Form
addTodo={this.addTodo}
handleSubmit={this.handleSubmit}
/>
<List
todos={this.state.todos}
deleteTodo={this.deleteTodo}
/>
</div>
);
}
}
export default App;
filter
在这里很有用。 - Michael ElliottdeleteTodo()
函数中:尝试使用const todos = [...this.state.todos]
。查看Spread Syntax
获取更多信息。 - Arman Charan