I’m seeing some odd behaviour with Blazor with event hooks and the firstRender
argument of OnAfterRender
.
My parent component creates a dynamic set of child components:
Parent:
@if (_childObjects != null)
{
@foreach (var childObject in _childObjects )
{
<ChildComponent ChildObject=@childObject />
}
}
Child:
[Parameter]
public ChildObject ChildObject { get; set; }
What happens is on clicking certain buttons that parent re-renders with a new set of child objects. I expect it to create new instances of ChildComponent
for that, which it partially does.
But somehow when it hits this code:
protected override void OnAfterRender(bool firstRender)
… at this point, the value of firstRender
is false and everything seems to be already initialised as per the previous render of the parent.
>Solution :
I expect it to create new instances of
ChildComponent
Why? Blazor sees a (Child) Component with a different parameter.
You can help the differ by adding @key, I think that will do what you want:
@foreach (var childObject in _childObjects )
{
<ChildComponent @key="childObject" ChildObject="childObject" />
}