我正在与React一起做我的第一个项目,我有一个App和一个ToDo。我正在定义一个deleteToDo
方法,并且希望该方法调用this.setState()
并将其传递给一个新数组,该数组不具有使用.filter()
删除的待办事项数组方法。我不想更改太多代码或引入更多复杂性。本质上,我想尽可能地保持直截了当。我仍然是React的初学者,所以这是一个很大的学习过程。我觉得我很近。
这是主要应用
import React, { Component } from 'react';
import './App.css';
import ToDo from './components/ToDo.js';
class App extends Component {
constructor(props) {
super(props);
this.state = {
todos: [
{ description: 'Walk the cat', isCompleted: true },
{ description: 'Throw the dishes away', isCompleted: false },
{ description: 'Buy new dishes', isCompleted: false }
],
newTodoDescription: ''
};
}
deleteToDo(index) {
const todos = this.state.todos.slice();
const todo = todos[index];
todo.deleteToDo = this.state.filter(index);
this.setState({ todos: todos });
}
handleChange(e) {
this.setState({ newTodoDescription: e.target.value })
}
handleSubmit(e) {
e.preventDefault();
if (!this.state.newTodoDescription) { return }
const newTodo = { description: this.state.newTodoDescription, isCompleted: false };
this.setState({ todos: [...this.state.todos, newTodo], newTodoDescription: '' });
}
toggleComplete(index) {
const todos = this.state.todos.slice();
const todo = todos[index];
todo.isCompleted = todo.isCompleted ? false : true;
this.setState({ todos: todos });
}
render() {
return (
<div className="App">
<ul>
{ this.state.todos.map( (todo, index) =>
<ToDo key={ index } description={ todo.description } isCompleted={ todo.isCompleted } toggleComplete={ this.toggleComplete } deleteToDo={ this.deleteToDo } />
)}
</ul>
<form onSubmit={ (e) => this.handleSubmit(e) }>
<input type="text" value={ this.state.newTodoDescription } onChange={ (e) => this.handleChange(e) } />
<input type="submit" />
</form>
</div>
);
}
}
export default App;
这是ToDo方面
import React, { Component } from 'react';
class ToDo extends Component {
render() {
return (
<li>
<button type="button" onClick={ this.props.deleteTodo} > delete </button>
<input type="checkbox" checked={ this.props.isCompleted } onChange={ this.props.toggleComplete } />
<span>{ this.props.description }</span>
</li>
);
}
}
export default ToDo;
答案 0 :(得分:0)
您对没有索引的切片和数组进行了切片,这可能就是删除操作无效的原因
deleteToDo(index) {
const todos = this.state.todos.slice(index, 1);
this.setState({ todos: todos });
}
答案 1 :(得分:0)
1)您需要在构造函数中绑定deleteToDo
方法
this.deleteToDo = this.deleteToDo.bind(this);
2)您需要在组件上设置一个与其索引相同的新属性。
<ToDo
key={index}
id={index}
description={ todo.description }
// ...
/>
3)然后,您可以将该索引作为参数传递给deleteToDo
(确保正确拼写方法名称)。
<button
type="button"
onClick={() => this.props.deleteToDo(this.props.index)}
>Delete
</button>
4)最后,您可以将deleteToDo
方法简化为以下内容:
deleteToDo(index) {
// Return a new array that doesn't
// have a row with a matching index
const todos = this.state.todos.filter((el, i) => i !== index);
this.setState({ todos });
}