[Blazor] LifeCycle

C#/Blazor 2023. 1. 2. 12:31
728x90

LifeCycle 이 생각보다 복잡?하여 실재 로그를 찍어보았습니다.

@page "/lifecycletest"

<PageTitle>LifeCycleTest</PageTitle>
<h1>----------------------------------------------</h1>
<h1>LifeCycleTest</h1>

<button class="btn btn-primary" @onclick="IncrementCount">Click me (@currentCount)</button>

<h3>@logMessage</h3>

@code {

    [Parameter]
    public int Increment { get; set; } = 1;

    private int currentCount = 0;
    private string logMessage = string.Empty;

    private void IncrementCount()
    {
        currentCount += Increment;
    }


    protected override void OnInitialized()
    {
        logMessage += "OnInitialized → ";
        base.OnInitialized();
    }

    protected override Task OnInitializedAsync()
    {
        logMessage += "OnInitializedAsync → ";
        return base.OnInitializedAsync();
    }

    public override Task SetParametersAsync(ParameterView parameters)
    {
        logMessage += "SetParametersAsync(ParameterView parameters) → ";
        return base.SetParametersAsync(parameters);
    }

    protected override void OnParametersSet()
    {
        logMessage += "OnParametersSet → ";
        base.OnParametersSet();
    }

    protected override Task OnParametersSetAsync()
    {
        logMessage += "OnParametersSetAsync → ";
        return base.OnParametersSetAsync();
    }

    protected override void OnAfterRender(bool firstRender)
    {
        logMessage += "OnAfterRender(" + firstRender + ") → ";
        base.OnAfterRender(firstRender);
    }

    protected override Task OnAfterRenderAsync(bool firstRender)
    {
        logMessage += "OnAfterRenderAsync(" + firstRender + ") → ";
        return base.OnAfterRenderAsync(firstRender);
    }

    protected override bool ShouldRender()
    {
        logMessage += "ShouldRender → ";
        return base.ShouldRender();
    }

}

결과

이 상태에서 버튼을 클릭하게되면 Render 관련 함수가 타게 됩니다.

결론순서

SetParametersAsync(ParameterView parameters)
→ OnInitialized
→ OnInitializedAsync
→ OnParametersSet
→ OnParametersSetAsync
→ (버튼클릭)
→ OnAfterRender(True)
→ OnAfterRenderAsync(True)
→ ShouldRender

[Source]
https://github.com/kei-soft/Blazor.AppTest/blob/master/Blazor.AppTest/Pages/LifeCycleTest.razor

 

GitHub - kei-soft/Blazor.AppTest

Contribute to kei-soft/Blazor.AppTest development by creating an account on GitHub.

github.com


참고
https://learn.microsoft.com/ko-kr/aspnet/core/blazor/components/lifecycle?view=aspnetcore-7.0 

 

ASP.NET Core Razor 구성 요소 수명 주기

ASP.NET Core Razor 구성 요소 수명 주기 및 수명 주기 이벤트를 사용하는 방법에 대해 알아봅니다.

learn.microsoft.com

 

728x90
Posted by kjun.kr
,