Can the state of the Counter in the example Blazor project be preserved between page switches?

前端 未结 4 953
情书的邮戳
情书的邮戳 2021-01-15 21:37

In the default example project for both server-side Blazor and WebAssembly Blazor projects, the Counter example resets to 0 every time you move between the pages. However, o

4条回答
  •  深忆病人
    2021-01-15 22:32

    I wrote an answer about Blazor state management that looks into this here:

    https://stackoverflow.com/a/65609519/3850405

    My recommendation would be an in-memory state container service.

    Example:

    StateContainer.cs

    public class StateContainer
    {
        public string Property { get; set; } = "Initial value from StateContainer";
    
        public event Action OnChange;
    
        public void SetProperty(string value)
        {
            Property = value;
            NotifyStateChanged();
        }
    
        private void NotifyStateChanged() => OnChange?.Invoke();
    }
    

    Program.Main (Blazor WebAssembly):

    builder.Services.AddSingleton();
    

    Startup.ConfigureServices (Blazor Server):

    services.AddSingleton();
    

    Pages/Component1.razor

    @page "/Component1"
    @inject StateContainer StateContainer
    @implements IDisposable
    
    

    Component 1

    Component 1 Property: @StateContainer.Property

    @code { protected override void OnInitialized() { StateContainer.OnChange += StateHasChanged; } private void ChangePropertyValue() { StateContainer.SetProperty($"New value set in Component 1 {DateTime.Now}"); } public void Dispose() { StateContainer.OnChange -= StateHasChanged; } }

    Shared/Component2.razor

    @inject StateContainer StateContainer
    @implements IDisposable
    
    

    Component 2

    Component 2 Property: @StateContainer.Property

    @code { protected override void OnInitialized() { StateContainer.OnChange += StateHasChanged; } private void ChangePropertyValue() { StateContainer.SetProperty($"New value set in Component 2 {DateTime.Now}"); } public void Dispose() { StateContainer.OnChange -= StateHasChanged; } }

    https://docs.microsoft.com/en-us/aspnet/core/blazor/state-management?view=aspnetcore-5.0&pivots=webassembly#in-memory-state-container-service-wasm

提交回复
热议问题