blazor - Why does Blazor renders component twice
问题描述
I have a simple Blazor component.
<div @onclick="HandleClick">Click me</div>
@code {
public async Task HandleClick()
{
await Task.Run(()=> System.Threading.Thread.Sleep(1000));
}
protected override void OnAfterRender(bool firstRender)
{
Console.WriteLine("Rendered");
}
}
When I click on the div "Rendered" is printed to console and after 1 sec again which means that blazor has rendered component twice. I understand that Blazor triggers an automatic re-render of a component as part of dispatching an event to it.
But why does it rerender after the task is completed? How can I avoid second render?
I have some JS interop in OnAfterRender lifecycle hook that now runs twice. I can add some sort of counter but that would polute my code and I would like to avoid that.
I my HandleClick
were a simple public void method then everything is ok but that is not always possible
解决方案
您可以像这样使用 firstRender 变量:
if(firstRender)
{
// Call JSInterop to initialize your js functions, etc.
// This code will execute only once in the component life cycle.
// The variable firstRender is true only after the first rendering of the
// component; that is, after the component has been created and initialized.
// Now, when you click the div element firstRender is false, but still the
// component is rendered twice, before the awaited method (Task.Run) is called,
// and after the awaited method completes. The first render occurs because UI
// event automatically invoke the StateHasChanged method. The second render
// occurs also automatically after an awaited method in an async method
// completes. This is how Blazor works, and it shouldn't bother you.
}
推荐阅读
- php - 在重新路由到 HTTPS 时删除 URL 末尾的 .html
- json - 基于 JSON 字符串子项的过滤列表
- swift - SwiftUI:如何使用 NavigationViews 切换到新的导航堆栈
- prolog - 在 prolog 中使用 not fact(something) 时出现控制错误
- mysql - MySQL:根据账单日期过去多少天显示汇总会费
- python - 计算在 Python 中导致错误的方法数
- php - 子集合操作
- python - 使用 selenium 批量执行 python 脚本(selenium 错误)
- fortran - 返回许多值的索引函数
- python - Flask-Sqlalchemy:具有 3 个主键的表,它们也是外键