我想在OnInitializedAsync上从db获得一次数据。我尝试使用tableLoading来判断,但这不是工作。
protected override async Task OnInitializedAsync()
{
if (tableLoading)
{
return;
}
tableLoading = true;
users = await userService.GetSome(1, userType);
_total = await userService.GetCount(userType);
tableLoading = false;
Console.WriteLine("OnInitializedAsync");
}发布于 2022-08-11 14:43:11
这是解决问题的官方方法。您必须在第一次加载期间持久化组件状态,以便您的服务不会在第二次加载期间被第二次调用。
首先,在应用程序体内添加<persist-component-state />标记助手:
<body>
...
<persist-component-state />
</body>然后将PersistentComponentState注入组件并使用如下所示:
@implements IDisposable
@inject PersistentComponentState ApplicationState
@code {
private IEnumerable<User> _users;
private int _total;
private PersistingComponentStateSubscription _persistingSubscription;
protected override async Task OnInitializedAsync()
{
_persistingSubscription =
ApplicationState.RegisterOnPersisting(PersistState);
if (!ApplicationState.TryTakeFromJson<IEnumerable<User>>("users", out var restoredUsers))
{
_users = await userService.GetSome(1, userType);
}
else
{
_users = restoredUsers;
}
if (!ApplicationState.TryTakeFromJson<int>("total", out var restoredTotal))
{
_total = await userService.GetCount(userType);
}
else
{
_total = restoredTotal;
}
}
private Task PersistState()
{
ApplicationState.PersistAsJson("users", _users);
ApplicationState.PersistAsJson("total", _total);
return Task.CompletedTask;
}
void IDisposable.Dispose()
{
_persistingSubscription.Dispose();
}
}发布于 2022-08-10 06:57:09
我是怎么认识blazor OnInitializedAsync的主管的?
它通常负载两次。
但是,如果您想加载它一次,在这种情况下,您可以转到_Host.cshtml并将render-mode="ServerPrerendered"更改为render-mode="Server",因此它将只被调用一次,因此它将只从数据库加载一次数据。
注意:要获得更多信息,您可以参考official documents here。
发布于 2022-08-11 05:49:21
我知道它通常会加载两次,我想知道这个函数何时运行,如何知道它在一次或两次上运行。这是我的解决方案。
static bool first = true;
protected override async Task OnInitializedAsync()
{
if (first)
{
first = false;
Console.WriteLine("first time");
return;
}
Console.WriteLine("second time");
}https://stackoverflow.com/questions/73286727
复制相似问题