I'm learning Blazor and trying to figure out how components lifecycle methods works.
In my WASM project, I've created a simple component:
public class TestComponent : ComponentBase
{
[Parameter]
public string Id { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
protected override void OnParametersSet()
{
base.OnParametersSet();
Console.WriteLine($"({Id}) {nameof(OnParametersSet)}()");
}
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
base.BuildRenderTree(builder);
Console.WriteLine($"({Id}) {nameof(BuildRenderTree)}()");
builder.AddContent(0, this.ChildContent);
}
}
And added 2 instances of this component on the page:
<TestComponent Id="TestComponent1">
<input class="input" type="text" value="" />
</TestComponent>
<TestComponent Id="TestComponent2">
<input class="input" type="text" value="" @onchange="() => { }" />
</TestComponent>
Now, I see this log in a browser console when page loads:
blazor.webassembly.js:1 (TestComponent1) OnParametersSet()
blazor.webassembly.js:1 (TestComponent2) OnParametersSet()
blazor.webassembly.js:1 (TestComponent1) BuildRenderTree()
blazor.webassembly.js:1 (TestComponent2) BuildRenderTree()
That is expected as the components are just created. If I update TestComponent1
value, nothing happens.
But if I update TestComponent2
value I see the same log. I guess that is because TestComponent2
have attached event handler, that causes component update every time. I'm stuck with the following questions:
Why updating
TestComponent2
value triggers lifecycle methods forTestComponent1
? How they are related?Why
OnParametersSet
is fired? According to official documentation, this method should be called:
after component is initialized or when the parent component re-renders
None of these are my case, IMO.