c# - 示例 Blazor 项目中计数器的状态是否可以在页面切换之间保留?

标签 c# blazor

在服务器端 Blazor 和 WebAssembly Blazor 项目的默认示例项目中,每次在页面之间移动时,计数器示例都会重置为 0。但是,在 ASP.NET React 示例项目中,计数器不会在页面切换之间重置。

有没有办法让像计数器这样的组件在 Blazor 中的页面导航之间保持状态(至少对于不进行任何服务器调用的 WebAssembly 项目)?

enter image description here

最佳答案

看起来这个确切的场景在 https://learn.microsoft.com/en-us/aspnet/core/blazor/state-management?view=aspnetcore-3.0#client-side-in-the-browser 中讨论过

似乎 Blazor 不能开箱即用,但您只需要使用 localStoragesessionStorage

使用 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/

相关文章:

c# - 如果 T 发生变化,则从 List<T> 中移除所有项目

c# - 动态生成 blazor mudblazor 表

c# - 将 asp.net core 中间件从库内部注入(inject)到特定位置

c# - VS 2017 .Net core 2.2 中缺少 Blazor 模板

json - 字符串对象未从 Controller 发送到 Razor 组件

c# - 如何在 HTTP 触发器 Azure Function 3.x 中获取操作 IS。附图片

c# - 键是一对整数的字典

c# - PDFsharp 页面大小和设置边距问题 c#

c# - 避免异步方法的事件委托(delegate)重新创建

c# - 替代 if..else 语句