[英]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.