当前位置:网站首页>Blazor University (12) - component lifecycle
Blazor University (12) - component lifecycle
2022-04-23 03:08: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/202204230301333457.html
边栏推荐
- 微软是如何解决 PC 端程序多开问题的
- SQL statement - DDL
- Miniapi of. Net7 (special section): NET7 Preview3
- Openfeign details show
- 一套关于 内存对齐 的C#面试题,做错的人很多!
- Dynamic sequence table + OJ
- 2022T电梯修理考试模拟100题及在线模拟考试
- What kind of experience is it to prepare for a month to participate in ACM?
- Cherno_ Game engine series tutorial (5): 101~
- 腾讯视频VIP会员,周卡特价9元!腾讯官方直充,会员立即生效!
猜你喜欢
Binary tree
AOT和单文件发布对程序性能的影响
Detailed explanation of distributed things
. net tip: talk about the problem that the scoped service cannot be obtained in the middleware structure
ASP.NET 6 中间件系列 - 条件中间件
What kind of experience is it to prepare for a month to participate in ACM?
The most easy to understand dependency injection and control inversion
TP5 customization in extend directory succeeded and failed. Return information
2022T电梯修理考试模拟100题及在线模拟考试
基于.NetCore开发博客项目 StarBlog - (1) 为什么需要自己写一个博客?
随机推荐
利用正反遍历来解决“字符的最短距离”问题
微软是如何解决 PC 端程序多开问题的
基于.NetCore开发博客项目 StarBlog - (1) 为什么需要自己写一个博客?
TP5 email (2020-05-27)
Impact of AOT and single file release on program performance
ASP.NET和ASP.NETCore多环境配置对比
先中二叉建树
Development notes of raspberry pie (12): start Advantech industrial control raspberry pie uno-220 Kit (I): introduction and operation of the system
MAUI初体验:爽
編碼電機PID調試(速度環|比特置環|跟隨)
2022T电梯修理考试模拟100题及在线模拟考试
How to count the number of all files in a directory under win10 system
C# WPF UI框架MahApps切换主题
[format] simple output (2)
Dynamic sequence table + OJ
TP5 inherits base and uses the variables in base
AspNetCore配置多环境log4net配置文件
Using stack to solve the problem of "mini parser"
Use of MySQL command line client and common commands
Yes Redis using distributed cache in NE6 webapi