本文介绍了使用钩子删除 React 中的子任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在删除待办事项应用中的子任务时遇到问题.我想从域"中删除选定的子任务,而是 handleRemoveSubtasks 将所有子任务一起删除.

I have a problem with removing subtasks in my to-do app. I want to remove selected subtask from "Domain", istead handleRemoveSubtasks removes all of the subtasks together.

这是我的沙箱:https://codesandbox.io/s/weathered-paper-niyc3

删除子任务在

const handleRemoveSubtasks = subtaskId => {
    useList(
      list.map(el => {
        console.log(el.tasks);
        console.log(subtaskId);
        console.log(el.tasks.filter(ele => ele.id !== subtaskId));
        return el.tasks.filter(ele => ele.id !== subtaskId);
      })
    );
  };

推荐答案

各种问题:

  • handleRemoveSubtasks 尝试访问 el.tasks 即使它不存在,所以它会抛出错误.
  • handleRemoveSubtasks 过滤器作为自己的 el 元素返回,而不是 el.tasks
  • handleRemoveSubtasks tries to access el.tasks even if it doesnt exist, so it throws an error.
  • handleRemoveSubtasks filter is returned as the own el element, instead of the el.tasks

检查以下代码:

  const handleRemoveSubtasks = subtaskId => {
    useList(
      list.map(el => {
        if (!el.tasks) return el // If no tasks, return the same element
        return {...el, tasks: el.tasks.filter(task => task.id !== subtaskId)} // if tasks, filter them by id
      })
    );
  };

这篇关于使用钩子删除 React 中的子任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 12:03