当前位置:网站首页>Blazor University (12) - component lifecycle
Blazor University (12) - component lifecycle
2022-04-22 01:25:00 【Dotnet cross platform】
Link to the original text :https://blazor-university.com/components/component-lifecycles/
Component lifecycle
Source code [1]
Blazor Components have many virtual methods that we can override to affect the behavior of the application . These methods are executed at different times in the component life cycle . The following figure outlines the flow of these lifecycle approaches .
Component lifecycle diagram

SetParametersAsync
This method is executed whenever the parent renders .
The parameters passed to the component are contained in ParameterView in . This is based on the state passed to the component ( give an example ) A good time to make asynchronous calls .
When you call middle note base.SetParametersAsync(parameters) when , Will be the of the component [Parameter] Properties assign their values .
This is also the correct place to assign default parameter values . For complete instructions , See optional routing parameters [2].
OnInitialized / OnInitializedAsync
once ParameterCollection The state of is assigned to the component [Parameter] attribute , These methods will be executed . This is related to SetParametersAsync It's just as useful , But you can use the state of the component .
This method is executed only once when the component is first created . If the parent changes the parameters of the component later , Skip this method .
Be careful : When the component is One @page, And our Blazor The application navigates to a new page that renders the same page URL when ,Blazor The current object instance of the page will be reused . Because the object is the same instance , therefore Blazor Will not call... On the object IDisposable.Dispose, It will not be executed again OnInitialized Method .
OnParametersSet / OnParametersSetAsync
If this is a new instance of the component , Then this method will OnInitializedAsync Immediately after that . If it is an existing component that is being re rendered because its parent component is being re rendered , It won't be implemented OnInitialized Method , But in SetParametersAsync Execute this method immediately after .
StateHasChanged
This method marks the component to render .
Whenever the component wants to notify Blazor When a change occurs that will result in a different render output , It will call this method . for example , stay Clock In the component , We might set up a loop 1 Second timer , And then execute StateHasChanged To re render at the right time .
Another use is to indicate Blazor Partial re rendering is performed through asynchronous methods .
private async Task GetDataFromMultipleSourcesAsync()
{
var remainingTasks = new HashSet<Task>(CreateTheTasks());
while (remainingTasks.Any())
{
Task completedTask = await Task.WhenAny(remainingTasks);
remainingTasks.Remove(completedTask);
StateHasChanged();
}
}
When waiting happens ( The first 6 That's ok ) Or when the method is completed ( The first 10 That's ok ), Will handle pair StateHasChanged Call to .
ShouldRender
This method can return false To prevent the rendering tree of the component from being recalculated . Please note that , This method is not performed the first time a component is created and rendered .
When we know that our state has not changed since the last rendering or only in a way that will result in rendering the same output , instructions Blazor Don't execute BuildRenderTree Operation can save processing time and improve the user experience .
This method is not performed when the component is rendered for the first time .
BuildRenderTree
This method renders the content of the component as a memory representation that should be rendered to the user (RenderTree[3]).
<h1>People</h1>
@foreach(Person currentPerson in people)
{
<ShowPersonDetails Person=@currentPerson/>
}
The preceding tag will add a... To the rendering tree h1, among “People” As its content . Then it will be people Each of the Person Create a ShowPersonDetails New examples .
If our component is later in people Use add ons to re render , Will create ShowPersonDetails A new instance of the component and add it to our component's rendering tree . If people There are fewer items in the , So some of the previously created ShowPersonDetails Component instances will be discarded from our component's rendering tree , If they do IDiposable, They will be executed Dispose().
Be careful : In order to improve rendering efficiency , When rendering tags in any type of loop , Please always use @key Instructions [4].
OnAfterRender / OnAfterRenderAsync
Every time Blazor Regenerate the rendering tree of the component [5] when , Will execute the last two methods . This may be due to the re rendering of the parent of the component 、 The user interacts with the component ( For example, mouse click ) Or component performs its function StateHasChanged Method to call the re rendered result .
One of these methods is called firstRender Parameters of . This parameter is only... When the method is called for the first time on the current component true, From there on, it will always be false. In case of additional component connection ( for example , adopt JavaScript), It's useful to know that this is the first rendering .
until OnAfterRender After method execution , Can be used safely through @ref Any reference to the component set by the directive .
<ChildComponent @ref=MyReferenceToChildComponent/>
@code
{
// This will be null until the OnAfterRender* methods execute
ChildComponent MyReferenceToChildComponent;
}
until OnAfterRender Method is executed and firstRender Set to true after , Use pass @ref Command set HTML Any reference to the element is safe .
<h1 @ref=MyReferenceToAnHtmlElement>Hello</h1>
@code
{
// This will be null until the OnAfterRender* methods execute
// with firstRender set to true
ElementReference MyReferenceToAnHtmlElement;
}
Dispose
Although this is not ComponentBase One of the life cycle methods , But if the component implements IDisposable, Once the component is deleted from its parent's rendering tree ,Blazor Will execute Dispose. To achieve IDisposable, We need to @implements IDisposable Add to our razor In file .
@implements IDisposable
<h1>This is MyComponent</h1>
@code {
void IDisposable.Dispose()
{
// Code here
}
}
Wait in the asynchronous lifecycle method
Please pay attention ,Blazor Don't wait for long-running asynchronous methods to complete before you can render components , It will trigger rendering as soon as possible .
This enables the component to perform background tasks ( For example, retrieving data from a server ) Render tags for users to view when .
SetParametersAsync
for the first time await The action of
Continue the life cycle process ( If it is a new instance, it is OnInitialized, Otherwise OnParametersSet)
The action of exiting the method
No further action
Be careful : base.SetParametersAsync The method must be anywhere in the method await Execute before the command , Otherwise it will throw InvalidOperationException.
OnInitializedAsync
for the first time await The action of
Rendering Components
The action of exiting the method
Continue the life cycle process
OnParametersSetAsync
for the first time await The action of
Rendering Components
The action of exiting the method
Continue the life cycle process
OnAfterRenderAsync
for the first time await The action of
No further action
The action of exiting the method
No further action
The simple rule is SetParametersAsync Is the only way you can't pause a lifecycle process by waiting for a task .
All other asynchronous methods can suspend lifecycle processes , Until the execution exits the method , And the first one await Will pass through BuildRenderTree Rendering , To prevent users from having to wait for updates .
OnAfterRenderAsync It may look like an exception , Because it will not perform further operations in any case . If we consider the fact that rendering is the end of the execution chain , Then we can think of it as a completion chain rather than doing nothing . As for waiting for rendering , if necessary , The programmer must call StateHasChanged Explicitly complete , otherwise OnAfterRenderAsync Waiting in will lead to an infinite loop .
Component life cycle with asynchronous waiting

Asynchronous methods and multiple waits
Blazor In asynchronous methods await The code executed on will only be executed for the first time await When the . Subsequent waiting does not result in multiple renderings . for example
protected override async Task OnParametersSetAsync()
{
// Automatically renders when next line starts to await
await Task.Delay(1000);
// No automatic render when next line starts to await
await Task.Delay(1000);
// No automatic render when next line starts to await
await Task.Delay(1000);
}
If we want to render at other points , Then we must be in all other await Before the statement is called StateHasChanged.
protected override async Task OnParametersSetAsync()
{
// Automatically renders when next line starts to await
await Task.Delay(1000);
// Explicitly render when next line starts to await
StateHasChanged();
await Task.Delay(1000);
// Explicitly render when next line starts to await
StateHasChanged();
await Task.Delay(1000);
}
More about how to safely use different threads running on the same component , See multithreaded rendering [6] part .
Reference material
[1]
Source code : https://github.com/mrpmorris/blazor-university/tree/master/src/Components/ComponentLifecycles
版权声明
本文为[Dotnet cross platform]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220104106134.html
边栏推荐
- PR carries out JPEG frame compression and exports it as AVI video
- matlab:进行控制系统仿真,使用ode45求解LC电路
- Spring recruit high frequency interview question: how to design the second kill system?
- sql server 2008使用over(PARTITION BY..ORDER BY.. ) 显示有语法错误
- Tencent Android development interview experience, HR's words pierced my heart
- Solve the problem that the idea web project does not have small blue dots
- 网络模型 LSTM模型内容详解
- 天边的彩虹很美丽
- 量化交易之vnpy篇 - 同步模块避开自成交风险、新增同步完成提示
- Can avi recorded by OBS be opened by ImageJ?
猜你喜欢

cybox靶机渗透测试

draw2d自定义仪表盘

Pytoch installation and troubleshooting of groupspatialsoftmax errors

Embedded GUI inventory - how many do you know?

精彩回顾 | DEEPNOVA x Iceberg Meetup Online《基于Iceberg打造实时数据湖》
![[high concurrency] Why is there a strange bug problem when writing long variables on a 32-bit multi-core CPU? After reading this article, I understand!](/img/66/5b03acd6653e84e43ea75cb2e2bae9.jpg)
[high concurrency] Why is there a strange bug problem when writing long variables on a 32-bit multi-core CPU? After reading this article, I understand!

腾讯T3大牛手把手教你,90%的人看完都说好
![[PRANET] thesis and code interpretation (RFB and aggregation) - cavy LAN](/img/58/de9e7290c5ef9ed970acf69ed9882a.png)
[PRANET] thesis and code interpretation (RFB and aggregation) - cavy LAN
![[PRANET] interpretation of main architecture ------- wmilk](/img/48/5459fc54809db4c8b71d16f1fae7f9.png)
[PRANET] interpretation of main architecture ------- wmilk

Solve the problem that the idea web project does not have small blue dots
随机推荐
js查找数组下标
PR如何调整导出的数据速率和总比特率
使用多个可选过滤器过滤 Eloquent 模型
算法面试经典100题,冲刺7天拿下Offer
Can avi recorded by OBS be opened by ImageJ?
一个朋友的方法
Landing example: take you to disassemble DDD in six steps
腾讯T3团队整理,被逼无奈开始狂啃底层技术
Solve the problem that the idea web project does not have small blue dots
Tencent team strength to create an introduction course to fluent, 1-3 years of Android Development Engineer Interview Experience Sharing
bluemoon靶机渗透测试
[PRANET] thesis and code interpretation (RESNET part) -- Jiang Nie
【PraNet】论文代码解读(损失函数部分)——Blank
Solve the problem that the idea web project does not have small blue dots
学习 Butterfly主题美化 这一篇就够了
In 2022, crud alone can't meet the interview and upgrading notes of large factories in spring recruitment
[PRANET] interpretation of main architecture ------- wmilk
PR进行jpeg的帧压缩,并导出为avi视频
05 Lua control structure
cybox靶机渗透测试