【问题标题】:Why does Blazor renders component twice为什么 Blazor 渲染组件两次
【发布时间】:2020-03-17 18:47:59
【问题描述】:

我有一个简单的 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 时,“已渲染”会打印到控制台并在 1 秒后再次打印,这意味着 blazor 已渲染组件两次。我了解 Blazor 会触发组件的自动重新渲染,作为向其分派事件的一部分。

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

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

【问题讨论】:

  • 当你使 HandleClick 不异步时它将运行。你看到的是在等待之前和之后的渲染。
  • 但是为什么在等待任务之后才渲染呢?
  • UI在await Task.Run前后刷新,看一下:stackoverflow.com/questions/56604886/…

标签: blazor blazor-server-side blazor-client-side


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    值得一读微软在this上的说明:

    【讨论】:

      猜你喜欢
      • 2020-07-11
      • 2020-09-07
      • 2022-10-02
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多