Loading

Blazor笔记-Component stages/life cycle

更新记录

注意:非教程。纯笔记,日常查询用的。需要教程的小伙伴找几本书看看即可哈哈,有Vue基础的话非常快,概念都是通的。非工作需要不建议深入学习Blazor,深入Vue吧,用的多,哈哈。

完整目录地址:https://www.cnblogs.com/cqpanda/p/17596348.html

点击查看
2024年3月7日 发布。
2023年8月1日 迁移笔记到博客。

Blazor component stages

A Blazor component can go through five stages:
image

image

SetParameters

This stage is triggered when the component is initially constructed (the parameters still not be set) or whenever the component's parameters updated from the URL or from the parent component. If the SetParametersAsync method is overridden, the OnParametersSet and OnParametersSetAsync methods should not be used.

Initialized

This is the stage where the component is fully constructed and the parameters are set.

protected override async Task OnInitializedAsync()
{

}

During the Initialize phase, you can perform tasks such as:

  • Fetching data from an API
  • Subscribing to events
  • Setting default values for properties
  • Executing JavaScript

If we are doing long-running tasks (such as getting data from a database), we should put that code in the OnInitializedAsync() method.

These methods will only run once. If we want to update the UI when a parameter changes, see OnParametersSet() and OnParametersSetAsync()

ParametersSet

In this phase, you can respond to changes in the parameters, which may originate from the parent component or the URL.
ParametersSet: As the name implies, this stage is triggered whenever the component's parameters are updated from the URL or from the parent component.

However, if you have overridden the SetParametersAsync method, then you should skip this stage entirely.

If we, for example, load data in the OnInitialized() method but it does use a parameter, the data won’t be reloaded if the parameter is changed, since OnInitialized() will only run once. We need to trigger a reload of the data in OnParametersSet() or OnParametersSetAsync(), or move the loading to that method.

image

protected override void OnParametersSet()
{
}

从 URL 获得参数,使用[SupplyParameterFromQuery]修饰符

[Parameter]
[SupplyParameterFromQuery]
public string? UrlParameter { get; set; }

AfterRender

triggered when the component passes the initialize stage or StateHasChanged called.

When the methods are being called, all the elements are rendered, so if we want/need to
call any JavaScript code, we have to do that from these methods (we will get an error if we try to make a JavaScript interop from any of the other lifecycle event methods). We also have access to a firstRender parameter, so we can only run our code on the first render.

Each time Blazor renders the UI, the AfterRender phase is triggered.
During this phase, there are a number of actions that can be taken, such as:
Utilizing a third-party library to format the UI.
Gathering data on user behavior for analytics purposes.

protected override async Task OnAfterRenderAsync(bool firstRender)
{
}

image

Dispose

This is the final step where the component is removed from the UI.
Developers should clean up resources to prevent memory leaks or unexpected behaviours.

dispose of a component, it should implement the IDisposable/IAsyncDisposable interface, as the Dispose/DisposeAsync method is not a default feature.

Some resources can be automatically collected by the garbage collector, but others may not. To free resources, you should:

  • Unsubscribe from events
  • Stop working tasks
  • Close open streams

To properly dispose of a component, you should use the @implements directive to implement the IDisposable interface and declare a public void Dispose() method to free resources. Here is an example code for the Initialize and Dispose phases:

@implements IDisposable

public void Dispose()
{
}

When you are disposing a resource in asynchronous, you can implement the IAsyncDisposable as well. For example:

@implements IAsyncDisposable

@code {
    public async ValueTask DisposeAsync()
    {
    }
}

Component Life Cycle Table

Each stage has at least one method that can be overridden.
Can customize each stage of the component lifecycle by overriding the corresponding method.
In cases where a stage has two methods, one synchronous and one asynchronous.
the synchronous method will execute first, followed by the asynchronous method.
The table below shows the methods associated with each stage and their order of execution:

Stage Method Executing order
SetParameters SetParametersAsync 1
Initialized OnInitialized 2
Initialized OnInitializedAsync 3
ParametersSet OnParametersSet 4
ParametersSet OnParametersSetAsync 5
AfterRender OnAfterRender 6
AfterRender OnAfterRenderAsync 7
Dispose Dispose 8
Dispose DisposeAsync

完整实例

@page "/"
@implements IDisposable
@implements IAsyncDisposable

<h1>Test</h1>

@code{
    public override async Task SetParametersAsync(ParameterView parameters)
    {
        Console.WriteLine("SetParametersAsync - Begin");
        await base.SetParametersAsync(parameters);
        Console.WriteLine("SetParametersAsync - End");
    }

    protected override void OnInitialized()
    {
        base.OnInitialized();
    }

    protected override Task OnInitializedAsync()
    {
        return base.OnInitializedAsync();
    }

    protected override void OnParametersSet()
    {
        base.OnParametersSet();
    }


    protected override Task OnParametersSetAsync()
    {
        return base.OnParametersSetAsync();
    }

    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
    }

    protected override Task OnAfterRenderAsync(bool firstRender)
    {
        return base.OnAfterRenderAsync(firstRender);
    }

    public void Dispose()
    {

    }

    public async ValueTask DisposeAsync()
    {

    }
}
posted @ 2024-03-07 15:33  重庆熊猫  阅读(0)  评论(0编辑  收藏  举报