【问题标题】:TypeError: Cannot read properties of undefined (reading 'filter')TypeError:无法读取未定义的属性(读取“过滤器”)
【发布时间】:2021-12-26 14:21:18
【问题描述】:

我正在尝试创建一个事件来删除按钮单击时的元素,但收到错误“TypeError: Cannot read properties of undefined (reading 'filter')”

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

【问题讨论】:

  • todos 可能不是一个数组。只有数组具有过滤器属性。
  • 没有名为id的属性

标签: reactjs element


【解决方案1】:

你必须检查元素是否存在,我希望它的数组带有id属性,如果它是undefined,那么在它上面调用.fliter没有意义,它肯定会抛出错误,只有在它有数据,这样可以解决问题,我也在我的项目中这样做,

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

你可以这样做,

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

【讨论】:

  • 这会将 todos 设置为 true 或 false。这有什么帮助?
  • @EmilKarlsson 问题不是未定义的调用过滤器,所以在调用之前检查一下,让我知道它是否有效
  • 第一个选项,带来错误 'setTodos' is not a function ,第二个选项...按钮点击没有任何反应
  • todos 可能不是一个数组。只有数组有过滤器属性
猜你喜欢
  • 2021-10-31
  • 2019-03-26
  • 2020-10-22
  • 2019-05-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 2021-11-24
  • 2021-12-20
相关资源
最近更新 更多