Skip to content

Blazor: StateHasChanged resets component state if it has child content #17178

@akorchev

Description

@akorchev

Describe the bug

For some reason invoking the StateHasChanged method of a Blazor page resets component state only if the component has child content.

To Reproduce

Complete application: https://github.com/akorchev/blazor-state-lost

  1. Add the following component to a default Blazor server-side application.
    <div style="border: 1px solid #ebebeb; margin: 16px; border-radius: 2px"    @onclick="@Toggle">
     Toggle (Expanded = @Expanded)
    
     @if (Expanded)
     {
         @ChildContent
     }
     </div>
    
     @code {
          [Parameter]
          public bool Expanded { get; set; }
    
          [Parameter]
          public RenderFragment ChildContent {get; set;}
    
          void Toggle()
          {
              Expanded = !Expanded;
          }
     }   
  2. Add this to Index.razor
    @page "/"
    
     Welcome to your new app.
    
     <Expander Expanded="true">
           <h1>Hello, world!</h1>
     </Expander>
    
     <Expander Expanded="true" />
     <button @onclick="@(() => StateHasChanged())">StateHasChanged</button
  3. Run the application and click on both component instances. They correctly update and show the current value of the Expanded property - False.
  4. Click the StateHasChanged button. The first component resets to its initial state (expanded). The second keeps its state.

Here is a GIF showing my experience.
blazor-state-lost

Note that only the component with child content is reset. Not sure if this is a bug or something by design. If it is the latter please suggest a workaround.

Further technical details

  • ASP.NET Core version: 3.1.100-preview1-014459

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

Status

Done

Relationships

None yet

Development

No branches or pull requests

Issue actions