gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:11:00 31 4
gpt4 key购买 nike

在服务器端 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com