简体   繁体   English

类型错误:无法读取未定义的属性(读取“过滤器”)

[英]TypeError: Cannot read properties of undefined (reading 'filter')

I am trying to create an event to delete elements on button click but get the error "TypeError: Cannot read properties of undefined (reading 'filter')"我正在尝试创建一个事件以在单击按钮时删除元素,但收到错误“TypeError:无法读取未定义的属性(读取‘过滤器’)”

const Todo = ({ text, todo, todos, setTodos }) => {
  const deleteHandler = () => {
    setTodos(todos.filter((el) => el.id !== todo.id));
  };

  return (
    <div className="todo">
      <li className="todo-item">{text}</li>
      <button className="complete-btn">
        <i className="fas fa-check"></i>
      </button>
      <button onClick={deleteHandler} className="trash-btn">
        <i className="fas fa-trash"></i>
      </button>
    </div>
  );
};

you have to check if element exists or not, i am hoping its array with id property, if its undefined , so no point in calling .fliter on it, it will surely throw error, call only when it have data, like this will fix the issue, i do this in my project too,你必须检查元素是否存在,我希望它的数组带有id属性,如果它是undefined ,所以在它上面调用.fliter毫无意义,它肯定会抛出错误,只有在它有数据时才调用,这样就可以解决这个问题,我也在我的项目中这样做,

const deleteHandler = () =>{
   setTodos(todos && todos.filter((el) => el.id !== todo.id));
};

you can do this instead,你可以这样做,

const deleteHandler = () =>{
   if(todos ){
      setTodos(todos.filter((el) => el.id !== todo.id));
   }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeError:无法读取未定义(读取“过滤器”)和未定义错误的属性 - React - TypeError: Cannot read properties of undefined (reading 'filter') and undefined error - React 未捕获的类型错误:无法读取未定义(读取“过滤器”)JavaScript 的属性 - Uncaught TypeError: Cannot read properties of undefined (reading 'filter') JavaScript 在 reactjs TypeError 中出现错误:无法读取未定义的属性(读取“过滤器”) - Getting error in reactjs TypeError: Cannot read properties of undefined (reading 'filter') 类型错误:无法读取未定义的属性(读取“过滤器”)Tanstack 表(反应) - TypeError: Cannot read properties of undefined (reading 'filter') Tanstack table (React) × 类型错误:无法读取未定义的属性(读取“推送”) - × TypeError: Cannot read properties of undefined (reading 'push') 类型错误:无法读取未定义的属性(读取“onSnapshot”) - TypeError: Cannot read properties of undefined (reading 'onSnapshot') 未捕获的类型错误:无法读取未定义的属性(读取“然后”)? - Uncaught TypeError: Cannot read properties of undefined (reading 'then')? TypeError:无法读取未定义的属性(读取“主”) - TypeError: Cannot read properties of undefined (reading 'main') TypeError:无法读取未定义的属性(读取“toLocaleString”) - TypeError: Cannot read properties of undefined (reading 'toLocaleString') TypeError:无法读取未定义的属性(读取“setRestaurants”) - TypeError: Cannot read properties of undefined (reading 'setRestaurants')
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM