为什么 Blazor 渲染组件两次

par*_*ite 6 blazor blazor-server-side blazor-client-side

我有一个简单的 Blazor 组件。

<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");
    }
}
Run Code Online (Sandbox Code Playgroud)

当我单击 div 时,“Rendered”被打印到控制台,并在 1 秒后再次打印,这意味着 blazor 已渲染组件两次。我知道 Blazor 会触发组件的自动重新渲染,作为向其分派事件的一部分。

但是为什么它在任务完成后重新渲染?如何避免二次渲染?

我在 OnAfterRender 生命周期钩子中有一些 JS 互操作,现在运行两次。我可以添加某种计数器,但这会污染我的代码,我想避免这种情况。我HandleClick是一个简单的 public void 方法,然后一切正常,但这并不总是可能的

Isa*_*aac 6

您可以像这样使用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. 
} 
Run Code Online (Sandbox Code Playgroud)