带有对象数组的Todo List应用程序的handleRemove函数



所以我让这个应用程序变得超级简单,但我无法让我的handleRemove正常工作。filteredTodos是所有相同todo的列表。这是我的密码。我甚至尝试过在线查看其他解决方案,但由于某种原因,handleRemove中的这个过滤函数不会过滤掉状态之外的任何内容。

import React, { Component } from 'react';
class Main extends Component {
constructor(props){
super(props);
this.state = {
todos: [],
inputValue: '',
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleRemove = this.handleRemove.bind(this);
}
handleChange = (e) => {
e.preventDefault();
this.setState({
inputValue: e.target.value
});
}
handleSubmit = (e) => {
e.preventDefault();
const newTodo = this.state.inputValue;
if (this.state.inputValue === ''){
alert('Please Enter a Todo!');
} else {
this.setState((prevState) => ({
todos: [...prevState.todos,
{
message: newTodo,
id: this.state.todos.length
}
]
}));
this.setState({inputValue:''});
}
}
handleRemove (id) {
const filteredTodos = this.state.todos.filter(todo => todo.id !== id);
this.setState({
todos: filteredTodos
});
console.log(filteredTodos);
}
render(){
const mappedTodos = this.state.todos.map((item, i) => 
<div key={i} id={this.state.todos[i].id}>
{item.message} <button type='submit' onClick={this.handleRemove}>X</button>
</div>
)
return(
<div className='main-page'>
<div className='input'>
<input type='text' placeholder='Enter Your Todo' value={this.state.inputValue} onChange={this.handleChange} />
<button type='submit' onClick={this.handleSubmit}>Add</button>
</div>
<div className='todos'>
{mappedTodos}
</div>
</div>
)
}
}
export default Main;

您的handleRemove函数需要一个id,您可以通过圆括号中的值来查看它

handleRemove (id)

要解决这个问题,你只需要像这样传递参数:

const mappedTodos = this.state.todos.map((item, i) => 
<div key={i} id={this.state.todos[i].id}>
{item.message} <button type='submit' onClick={this.handleRemove(this.state.todos[i].id)}>X</button>
</div>
)

最新更新