为什么Blazor两次渲染组件

我有一个简单的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");
    }
}

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

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

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

myidgy 回答:为什么Blazor两次渲染组件

您可以像这样使用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. 
} 
,

我遇到了同样的问题,但我的解决方案与@enet 提到的不同。

如果您通过循环显示组件(例如 foreach 循环),则需要在组件上设置 @key 属性。在我的情况下,我有相同的组件,当然它接收具有不同唯一键的相同类型的对象,但 Blazor 无法区分两者。因此,当两者之一的数据发生变化时,Blazor 会生成所有这些。

当您传递 @key="Your-unique-key" 时,Blazor 会监视该键而不是整个模型实例。

值得阅读微软关于 this 的说明:

本文链接:https://www.f2er.com/3055589.html

大家都在问