我有一个组件:
const handleToggleTodo = React.useCallback(async (_id) => {
try {
const todo = TodoDataService.findOne({ _id });
const updated = todo.open ? Todo.close(todo) : Todo.reopen();
await TodoDataService.update(_id, updated);
} catch (error) {
toast.error(error.message);
}
}, []);
当我使用这个组件时,我得到这个错误:Rendered more hooks than during the previous render
。当我删除“useCallback”时,我不再收到该错误:
const handleToggleTodo = async (_id) => {
try {
const todo = TodoDataService.findOne({ _id });
const updated = todo.open ? Todo.close(todo) : Todo.reopen();
await TodoDataService.update(_id, updated);
} catch (error) {
toast.error(error.message);
}
}
如果能解释一下此修复程序的工作原理,那就太好了。这是正确的决定吗?如果没有,我是否需要使用条件运算符或其他东西? 完整的组件代码:
export default function TodoTable({ todos }) {
const handleRemoveTodo = React.useCallback((_id) => {
TodoDataService.remove(_id);
}, []);
if (!todos.length) return <div>No todos in your list</div>;
const handleToggleTodo = React.useCallback(async (_id) => {
try {
const todo = TodoDataService.findOne({ _id });
const updated = todo.open ? Todo.close(todo) : Todo.reopen();
await TodoDataService.update(_id, updated);
} catch (error) {
toast.error(error.message);
}
}, []);
return (
<div className="table-full-width table-responsive">
<Table>
<tbody>
{todos.map((item) => (
<TodoItem
key={item._id}
{...item}
onChange={() => handleToggleTodo(item._id)}
onRemove={() => handleRemoveTodo(item._id)}
/>
))}
</tbody>
</Table>
</div>
);
}