为什么Blazor两次渲染组件 [英] Why does Blazor renders component twice
问题描述
我有一个简单的Blazor组件.
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");
}
}
当我单击div时,"Rendered"已打印到控制台,并在1秒钟后再次打印,这意味着blazor已两次渲染了组件.我了解Blazor会触发自动重新渲染组件,这是向该组件分发事件的一部分.
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?
我在OnAfterRender生命周期挂钩中有一些JS互操作,现在可以运行两次.我可以添加某种计数器,但这会污染我的代码,我想避免这种情况.我的 HandleClick
是一个简单的public void方法,那么一切正常,但这并不总是可能的
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变量:
You can use the firstRender variable like this:
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两次渲染组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!