Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

blazor - 可以在页面切换之间保留Blazor示例项目中Counter的状态吗?(Can the state of the Counter in the example Blazor project be preserved between page switches?)

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.

(在服务器端Blazor和WebAssembly Blazor项目的默认示例项目中,每次在页面之间移动时,Counter示例都会重置为0。)

However, on the ASP.NET React example project, the Counter does not reset between page switches.

(但是,在ASP.NET React示例项目中,计数器不会在页面切换之间重置。)

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)?

(是否有一种方法可以使诸如Counter之类的组件在Blazor中的页面导航之间保留状态(至少对于不进行任何服务器调用的WebAssembly项目)?)

在此处输入图片说明

  ask by pkr298 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

(似乎在https://docs.microsoft.com/zh-cn/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 .

(似乎Blazor并没有开箱即用,但是您只需要使用localStoragesessionStorage 。)

Using the Blazor.Extensions.Storage NuGet package ( https://github.com/BlazorExtensions/Storage ):

(使用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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...