致敬。我正在将简单的todoApp从组件移动到钩子。所以这里有一个问题:我正在从我的 App.js(最高一个(文件中的待办事项数组创建一个删除器,并将其传递给另一个组件。
所以这里是:
const App = () => {
const [todoData, onDeleted] = useState([
{ label: "Drink Coffee", important: false, id: 1 },
{ label: "Make Awesome App", important: true, id: 2 },
{ label: "Have a lunch", important: false, id: 3 }
]);
const deleteHandler = id => {
todoData.filter(obj => obj.id !== id);
};
return(
<TodoList todos={todoData} onDeleted={onDeleted(id => deleteHandler(id)))} />
)
在待办事项列表中.js我这样做。
<li key={id} className="list-group-item">
<TodoListItem {...itemProps} onDeleted={() => onDeleted()} />
</li>
在待办事项列表中.js我这样做:
<button
type="button"
className="btn btn-outline-danger btn-sm float-right"
onClick={onDeleted}
>
所以。。。我真的不知道如何正确传递元素的 id 来删除处理程序,我也得到"类型错误:无法读取未定义的属性'过滤器'"。我做错了什么,我该如何解决?
实现删除的最佳方法是执行以下操作:
const App = () => {
// Renamed onDeleted to setTodoData, to keep code cleaner.
const [todoData, setTodoData] = useState([
{ label: "Drink Coffee", important: false, id: 1 },
{ label: "Make Awesome App", important: true, id: 2 },
{ label: "Have a lunch", important: false, id: 3 }
]);
const onDeleted = id => {
setTodoData(todoData => todoData.filter(obj => obj.id !== id));
};
// Avoid passing anonymous functions as props, it may trigger re-renders and worsen performance.
return (
<TodoList todos={todoData} onDeleted={onDeleted} />
);
}
// Make sure to pass id here, I assume it's in itemProps, replaced the anonymous function with some prop drilling.
<li key={id} className="list-group-item">
<TodoListItem {...itemProps} onDeleted={onDeleted} />
</li>
现在对于按钮部分(假设 id 存在于道具上(:
const deleteItem = () => {
props.onDeleted(props.id);
};
<button
type="button"
className="btn btn-outline-danger btn-sm float-right"
onClick={deleteItem}
>
通常为了避免道具钻孔的问题(通过多个组件传递相同的道具(,我建议使用 Redux(具有很好的钩子,如 useSelector 和 useDispatch(。此外,请避免将匿名函数传递给组件属性。