javascript - 复选框更新请求,ReactJS
问题描述
我正在制作简单的待办事项列表应用程序,一切正常。我只是想确保我做对了,没有任何错误。我担心复选框更新部分,请检查代码并告诉我是否做错了什么。
这是 Checkboxes 的 put 方法
checkBoxRouteUpdate = () => {
let {todos} = this.state
let newArray = [...todos]
axios
.put(`http://localhost:8080/checkEdit/`, {
checked: newArray.every(todo => todo.checked)
}).then((res) => {
console.log("res", res);
})
.catch((err) => {
console.log("err", err);
});
}
检查所有这些
checkAllCheckBox = () => {
let {todos} = this.state
let newArray = [...todos]
if (newArray.length !==0) {
newArray.map(item => {
if (item.checked === true) {
return item.checked = false
} else {
return item.checked = true
}
})
this.checkBoxRouteUpdate()
this.setState({todos: newArray})
}
}
检查单个复选框
checkSingleCheckBox = (id) => {
let {todos} = this.state
let newArray = [...todos]
newArray.forEach(item => {
if (item._id === id) {
item.checked = !item.checked
axios
.put(`http://localhost:8080/edit/${id}`,{
checked:item.checked
})
.then(res => {
this.setState({todos: newArray})
console.log('res',res)
})
.catch((err) => {
console.log("err", err);
});
} else {
}
})
}
仅删除选中的项目
deleteAllChecked = () => {
const todos = this.state.todos.filter((item => item.checked !== true))
axios
.delete('http://localhost:8080/deleteAllChecked')
.then((res) => {
this.setState({ todos,
pageCount: Math.ceil(todos.length / 10)})
console.log("res", res);
})
.catch((err) => {
console.log("err", err);
});
}
解决方案
您可以通过其他方式选中/取消选中它们
this.checkBoxRouteUpdate()
this.setState(state => ({
...state,
todos: state.todos.map(todo => ({
...todo,
checked: !item.checked
}))
}))
我认为你应该在 api 返回 ok 状态后删除
.then((res) => {
this.setState(state => {
const todos = state.todos.filter((item => item.checked !== true));
return {
...state,
todos,
pageCount: Math.ceil(todos.length / 10)
}
})
推荐阅读
- python - 如何计算 Pandas 数据框中列中唯一元素的数量
- acumatica - 通过基于合同的 REST API 查询带有感叹号的自定义字段时出现语法错误
- reactjs - kotlin 多平台 + 反应
- python - 如果可以获取 Spark 中的分区数,为什么无法确定数据帧中的分区?
- android - 带有 react-native 的 Firebase 中的“auth/app-not-authorized”
- python - 具有固定和动态长度的 Python 拆分输出列
- python - 是否可以在后端编写 C# 代码并将结果发送回 dart?
- git - GitHub 离开 master
- vue.js - 在 nuxt/vue 中来自 apollo 的数据发生变化后,子元素不更新道具
- ssl - 如何为覆盖父域的三节点服务器域创建 tls 证书?