如何在页面重新加载时在blazor Web程序集中的单例状态容器中保留值 [英] how to persist value in a singleton state container in blazor web assembly on page reload

查看:77
本文介绍了如何在页面重新加载时在blazor Web程序集中的单例状态容器中保留值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我练习和学习 blazor网站组装.我正在学习组件之间进行通信的方式.一种这样的方法是使用状态容器.这可以按预期工作,但不能保持页面刷新的价值.

I practicing and learning blazor web assembly. I'm learning on the ways to communicate between the components. One such way is to use a state container. This works as expected however it does not sustain value on page refresh.

这是我的状态容器类,

AppState :

AppState:

public class AppState
{
    public string SomeText { get; set; }
}

我已在 Program.cs

builder.Services.AddSingleton<AppState>();

通过此设置,我可以在多个组件中进行 @inject AppState 并共享值,就像可以在一个组件中进行设置并在另一个组件中进行获取一样.一切顺利.刷新后,我丢失了 SomeText 属性中的值.

with this setup, I'm able to @inject AppState in multiple components and share the value like I can set it in one component and get it in another component. All goes well. When I refreshed, I lost the value in SomeText property.

进一步搜索之后,我从文章-Blazor的服务寿命中注意到了

After further googling, I noticed from this article - Service Lifetimes in Blazor that,

Blazor仅在客户端上运行,并且刷新整个页面或在新标签页中打开应用会创建一个新的应用程序.

Blazor is running on the client only and a full page refresh or opening the app in a new tab creates a new instance of the application.

但是是否有任何解决方法或解决方案来保留该价值?我想到的只是浏览器 localstorage .我做对了吗?请提出您的建议,如果我错了,请纠正我?

But is there any workaround or solution to retain the value? All that comes to my mind is browser localstorage. Am I doing correct? Your suggestions please and correct me if I'n wrong?

推荐答案

重新加载页面等同于关闭应用程序并重新启动它,内存中的所有内容均已消失.

Reloading the page is the equivalent of shutting down an app and restarting it, anything in memory is gone.

我自己没有使用过它,但是我听说@chrissainty的Blazored/localstorage很好.但是问题在于,您会遇到多个选项卡,将状态设置为冲突值.

I've not used it myself but I've heard Blazored/localstorage by @chrissainty is good. But the problem there is you'd have multiple tabs fighting to set the state to conflicting values.

所以您要么需要选项卡间的通信,就可以通过事件来完成标签或窗口之间的通信

So you'd either need inter-tab communication, which can be done with events Communication between tabs or windows

不过,如果可能的话,请使用客户端作为用户界面,并使客户端与服务器(然后与数据库)通信以保持持久性.

If possible though, use your client as the UI and have it communicate with a server (and then to a db) for persistence.

这篇关于如何在页面重新加载时在blazor Web程序集中的单例状态容器中保留值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆