useState 不更新状态
我在下面的代码中更改了 isDeleting 的状态。此状态用于显示删除按钮上的微调器。删除任务完成后,此状态将更改为 false
const { deleteExpense } = apiExpenses();
const [isDeleting, setIsDeleting] = useState(false)
const handleDeleteCompleted = () => {
setIsDeleting(true)
const response = deleteExpense(fetchExpenseId);
if(response) {
setOpenConfirmDelete(false);
setIsDeleting(false)
}
};
\\in JSX
<ButtonError
onClick={handleDeleteCompleted}
size="large"
sx={{
mx: 1,
px: 3,
}}
variant="contained"
startIcon={
isDeleting ? <CircularProgress size="1rem" /> : null
}
disabled={isDeleting}
>
{t("Delete")}
</ButtonError>
当 handleDeleteCompleted
函数运行时,它不会更改 isDeleting
的状态,并且如果我始终对其进行控制台保持false
。它还运行 deleteExpense
函数。
因此,旋转器永远不会弹出。
这里出了什么问题?
I have below code where I change state of isDeleting
. This state is used to show the spinner on the delete button. Once the delete task is finished this state is changed to false
const { deleteExpense } = apiExpenses();
const [isDeleting, setIsDeleting] = useState(false)
const handleDeleteCompleted = () => {
setIsDeleting(true)
const response = deleteExpense(fetchExpenseId);
if(response) {
setOpenConfirmDelete(false);
setIsDeleting(false)
}
};
\\in JSX
<ButtonError
onClick={handleDeleteCompleted}
size="large"
sx={{
mx: 1,
px: 3,
}}
variant="contained"
startIcon={
isDeleting ? <CircularProgress size="1rem" /> : null
}
disabled={isDeleting}
>
{t("Delete")}
</ButtonError>
When handleDeleteCompleted
function runs it does not change state of isDeleting
and if I console it always stay in false
. It runs deleteExpense
function as well.
and for that reason, the spinner never popup.
What is getting wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
deleteExpense()
应该是一个async
函数吗?在您当前的示例中,您将其视为同步函数。这导致设置setIsDeleting(true)
和setIsDeleting(false)
之间没有时间,因为 React 在这些操作同步发生时将其捆绑在一起,后者会覆盖前者,并且您可以从未真正调用setIsDeleting(true)
。要解决此问题,请尝试使您的函数
异步
Should
deleteExpense()
be anasync
function? In your current example you're treating it as a synchronous function. This results in that there is no time between settingsetIsDeleting(true)
andsetIsDeleting(false)
because React bundles these actions when they happen synchronously, the latter overrides the former and you never actually invokesetIsDeleting(true)
.To fix this, try making your function
async