在服务器端 Blazor 和 WebAssembly Blazor 项目的默认示例项目中,每次在页面之间移动时,计数器示例都会重置为 0。但是,在 ASP.NET React 示例项目中,计数器不会在页面切换之间重置。
有没有办法让像计数器这样的组件在 Blazor 中的页面导航之间保持状态(至少对于不进行任何服务器调用的 WebAssembly 项目)?
最佳答案
看起来这个确切的场景在 https://learn.microsoft.com/en-us/aspnet/core/blazor/state-management?view=aspnetcore-3.0#client-side-in-the-browser 中讨论过
似乎 Blazor 不能开箱即用,但您只需要使用 localStorage
或 sessionStorage
。
使用 Blazor.Extensions.Storage
NuGet 包 ( 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);
}
}
关于c# - 示例 Blazor 项目中计数器的状态是否可以在页面切换之间保留?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59126869/