首页 > 解决方案 > 复选框更新请求,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);
        });
}

标签: javascriptreactjs

解决方案


您可以通过其他方式选中/取消选中它们

  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)
  }
})


推荐阅读