Blazor: Detailed Explanation of Component Lifecycle and Refresh Mechanism

foreword

For componentization, the life cycle is a must-knowledge. Only by mastering the life cycle can we better set the data changes.

Blazor Lifecycle Microsoft Documentation

life cycle

subcomponent settings

We set up some functions to listen to these lifecycle event updates.

 private void Print(string str)
 {
    
    
     System.Console.WriteLine($"子组件,{
      
      str}");
 }
 protected override void OnInitialized()
 {
    
    
     Print($"OnInitialized!");

     base.OnInitialized();
 }


 protected override void OnAfterRender(bool firstRender)
 {
    
    
     Print($"OnAfterRender,firstRender:{
      
      firstRender}");
     base.OnAfterRender(firstRender);
 }

 protected override void OnParametersSet()
 {
    
    
     Print($"OnParametersSet!");
     base.OnParametersSet();
 }

 public override Task SetParametersAsync(ParameterView parameters)
 {
    
    
     Print($"SetParametersAsync!");

     return base.SetParametersAsync(parameters);
 }

event refresh

Avoid Overriding Parameters in ASP.NET Core Blazor

Rendering conventions for ComponentBase

Blazor life cycle

ASP.NET Core Blazor Performance Best Practices

Why is it forced to refresh when non-basic elements are passed in?

Reason 1: The delegate type passed in does not belong to a non-base element.
insert image description here
insert image description here

insert image description here
insert image description here

auto refresh logic

  • When the value of the parent element is modified
    • If the value of the parent element is the same as the previous value, no refresh will occur
    • If different, subcomponents are notified individually to refresh.
  • If a non-basic element is passed in, such as a callback function
    • Every time the refresh is forced, because C# does not know whether the callback function has been modified. And all elements are forced to refresh.

How to solve the forced refresh problem of delegated events

  • Declare two elements, one is public and the other is private
  • When the subcomponent's creation event OnInitialized, pay public to private.
  • No matter how you update it afterwards, the value of private is not controlled by the parent component.

Guess you like

Origin blog.csdn.net/qq_44695769/article/details/132256478