reactjs - 如何删除待办事项列表reactjs中的所有选定任务
问题描述
我是 reactjs 的新手,我正在尝试制作一个 todolist,我可以在其中一次删除所有选定的任务。虽然我能够一一删除每个任务,但不知道如何在删除方法中传递所选任务的索引或 ID。我在代码末尾添加了该按钮。那么任何人都可以帮我找出如何将选定任务的索引或 ID 传递给按钮的删除方法?有没有可能只有在选择任何任务时才会出现删除?
import {Jumbotron, Input, Label, Button, Row, Col, Navbar, NavbarBrand} from 'reactstrap';
import { Control, LocalForm, Errors } from 'react-redux-form';
//for validations
const required = (val) => val && val.length;
const minLength = (len) => (val) => val && (val.length >= len);
class Task extends Component {
constructor(props) {
super(props);
let email = localStorage.getItem("email")
if (!email) {
this.props.history.push("/login")
}
this.state = {
email: email,
tasks: [],
todoText: "",
done: false
};
};
// For todoText (textbox entry)
onChangeInput = e => {
this.setState({ todoText: e.target.value });
}
//for Adding the task
onSubmitTodo = (values) => {
const payload = {
email: this.state.email
}
const todoText = this.state.todoText
fetch('http://localhost:3000/tasks', {
method: 'POST',
headers: {
'Content-type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
email: payload.email,
tasks: todoText,
})
})
.then((response) => {
if (response.ok) {
return this.setState(({ tasks }) => ({
tasks: [...tasks, { id: tasks.length, name: values.todoText, done: false }],
todoText: ""
}));
}
return Promise.reject(response);
})
.catch(function (error) {
console.warn('Something went wrong', error)
})
};
//for using tasks as done or not done
onChangeBox = item => {
this.setState(({ tasks }) => ({
tasks: tasks.map(el =>
el.id === item.id ? { ...el, done: !el.done } : el)
}));
};
//for deleting selected tasks
handleDel = item => {
const payload = {
email: this.state.email
}
fetch('http://localhost:3000/tasks', {
method: 'DELETE',
headers: {
'Content-type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
email: payload.email,
tasks: [item.id]
})
})
.then((response) => {
if (response.ok) {
return this.setState(({ tasks }) => ({
tasks: tasks.filter(el => el.id !== item.id)
})),
this.componentDidMount();
}
})
};
componentDidMount() {
const payload = {
email: this.state.email
}
fetch('http://localhost:3000/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
},
body: JSON.stringify(payload)
})
.then(res => res.json())
.then((data) => {
let tasks = []
data.tasks.map((item, index) => {
tasks.push({ id: index, name: item, done: false })
})
this.setState({ tasks: tasks })
})
}
render() {
const List = ({ list, onChangeBox, handleDel }) => (
<ul className='ul'>
{
list.map((item) => ( //list view for todo list
< li key={item.id} className="list" style={{ textDecoration: item.done ? "line-through" : "" }}>
<Input type="checkbox" onClick={() => onChangeBox(item)} defaultChecked={item.done} style={{ marginRight: 20 }} />
{item.name}
<span type="button" onClick={() => handleDel(item)} style={{ marginLeft: 50 }} className="fa fa-trash-o fa-lg "></span>
</li>
))
}
</ul>
);
const { tasks, todoText } = this.state;
return (
<>
<Navbar dark color='dark'>
<div className="container">
<span className="fa fa-tasks fa-lg"></span>
<NavbarBrand href="/" > To Do
<br /> keep your tasks in check </NavbarBrand>
</div>
</Navbar>
<Jumbotron>
<div className="container">
<LocalForm onSubmit={(values) => this.onSubmitTodo(values)}>
<Row className="form-group">
<Label htmlFor="todoText" md={1}><h4>Task</h4></Label>
<Col md={3}>
<Control.text model=".todoText" autoComplete="off" value={todoText}
onChange={this.onChangeInput}
validators={{
required, minLength: minLength(1)
}}
className="form-control col-md-3" />
<Errors className="text-danger"
model=".todoText"
show="touched"
messages={{
required: 'required',
minLength: 'Must be Greater than or equal to 1 characters'
}}
/>
</Col>
<Col md={2}>
<Button type="submit" color="success" >
ADD TASK
</Button>
</Col>
</Row>
</LocalForm> <br />
{tasks.length ? <List list={tasks} onChangeBox={this.onChangeBox} handleDel={this.handleDel} /> : <div className="notask">You don't have any pending tasks...Yay!!!</div>}
<Button className="button" >Delete</Button>
</div>
</Jumbotron>
</>
);
}
}
export default Task;
解决方案
这里的主要问题是您无法选择多个任务,因为您的复选框目前仅用于将任务标记和取消标记为已完成。如果您想通过复选框处理删除多个任务,您需要更改完整/不完整逻辑的工作方式。(不过,我不会在下面的解决方案中介绍这一点,因为这不是您的问题所在。)
- 重新组织您的任务逻辑,使复选框仅用于通过将任务标记为而不是来选择任务。
onChangeBox
selected
done
- 单击“删除”按钮时,通过执行以下操作更新您的任务状态:
this.setState(({ tasks }) => ({ tasks: tasks.filter(task => !task.selected) }));
这将允许您删除一个或多个任务,但现在您必须以不同的方式实现任务完成逻辑。
推荐阅读
- jquery - 减去具有相同类名的输入字段
- symfony - 具有 3 个实体的 Symfony 交集实体
- java - 在评估代码或返回已经过去之前查询不返回值
- vim - 移动窗口的 Vim 键盘快捷键不起作用
- asp.net-mvc - POST Fetch .Net Core
- java - 如何在 Java 中将 Scala 回调函数设置为参数?
- spring-boot - 如何在 JUnit 测试中正确模拟 FeignClient 响应
- javascript - 如何使用旋转值通过变换或数学旋转 SVG 矩形?
- rxjs - Observable 在发出数据时是否必须完成?
- php - Composer 使用本地 Git 捆绑包,就像使用 Git 存储库一样