gpt4 book ai didi

blazor - 为什么 Blazor 渲染组件两次

转载 作者:行者123 更新时间:2023-12-03 14:23:54 31 4
gpt4 key购买 nike

我有一个简单的 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 会触发组件的自动重新渲染,作为向其分派(dispatch)事件的一部分。

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

我在 OnAfterRender 生命周期钩子(Hook)中有一些 JS 互操作,现在运行了两次。我可以添加某种计数器,但这会污染我的代码,我想避免这种情况。
我的 HandleClick是一个简单的公共(public)无效方法,那么一切都很好,但这并不总是可能的

最佳答案

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

关于blazor - 为什么 Blazor 渲染组件两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58981661/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com