问题
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, on the ASP.NET React example project, the Counter does not reset between page switches.
Is there a way for a component like the Counter to preserve state between page navigation in Blazor (at least for the WebAssembly project that isn't making any server calls)?
回答1:
It looks like this exact scenario is discussed in https://docs.microsoft.com/en-us/aspnet/core/blazor/state-management?view=aspnetcore-3.0#client-side-in-the-browser
Seems Blazor just doesn't handle it out-of-the-box, but you just need to use localStorage
or sessionStorage
.
Using the Blazor.Extensions.Storage
NuGet package (https://github.com/BlazorExtensions/Storage):
@page "/counter"
@inject ISessionStorage SessionStorage
@using Blazor.Extensions.Storage.Interfaces
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
protected override async Task OnInitializedAsync()
{
currentCount = await SessionStorage.GetItem<int>("counter");
}
private async void IncrementCount()
{
currentCount++;
await SessionStorage.SetItem<int>("counter", currentCount);
}
}
回答2:
I cover this in my article (works for server side Blazor as well as client side (WebAssembly) Blazor): Implementing State Management In Blazor
Add a class called CounterState.cs using the following code:
public class CounterState
{
public int CurrentCount { get; set; }
}
Register this class, using Dependency Injection, in the the Startup.cs:
services.AddScoped<CounterState>();
Add the following code to the top of the .razor code page:
@inject CounterState CounterState
Change the following code:
<p>Current count: @currentCount</p>
To:
<p>Current count: @CounterState.CurrentCount</p>
Finally, change the code section to the following:
@code {
void IncrementCount()
{
// ** SESSION STATE
int CurrentCount = CounterState.CurrentCount;
CurrentCount++;
// Set Current count on the Session State object
CounterState.CurrentCount = CurrentCount;
}
}
来源:https://stackoverflow.com/questions/59126869/can-the-state-of-the-counter-in-the-example-blazor-project-be-preserved-between