问题描述
在服务器端Blazor和WebAssembly Blazor项目的默认示例项目中,每次在页面之间移动时,Counter示例都会重置为0.但是,在ASP.NET React示例项目中,计数器不会在页面切换之间重置.
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.
Counter之类的组件是否可以保留Blazor中页面导航之间的状态(至少对于不进行任何服务器调用的WebAssembly项目)?
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)?
推荐答案
似乎Blazor并没有开箱即用,但您只需要使用localStorage
或sessionStorage
.
Seems Blazor just doesn't handle it out-of-the-box, but you just need to use localStorage
or sessionStorage
.
使用Blazor.Extensions.Storage
NuGet软件包( https://github.com/BlazorExtensions/Storage ):
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);
}
}
这篇关于可以在页面切换之间保留Blazor示例项目中的Counter状态吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!