加载组件加载数据 [英] Loading data on component load
问题描述
人们会认为这是一项简单的任务.但是如何在组件加载时调用服务方法而不触发两次?
One would think this is an easy task. But how do I call a service method on component load without it firing twice?
目前 -
protected override async Task OnInitializedAsync()
{
await Initialize();
}
private async Task Initialize()
{
Video = await _VideoService.GetAsync(Id);
}
现在这被调用了两次,对于相同的信息两次访问数据库似乎不是一个好主意.
Right now this gets called twice, which doens't seem like a good idea to hit the database twice for the same information.
我已经尝试在下面使用它,但它会在每次渲染之前抛出错误.
I've tried just having this below, but it will throw an error before it even renders everytime.
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if(firstRender)
{
await Initialize();
}
}
推荐答案
OnInitializedAsync
用于初始化组件的生命周期方法被执行两次:
- 静态预渲染组件时.
- 在建立服务器连接之后.
这是设计使然 - 检查 预渲染后的有状态重新连接 和本文的其他部分,以找出在您的情况下加载数据的安全方法.也许是 SetParametersAsync
或 OnParametersSetAsync
It is by design - check Stateful reconnection after prerendering and other sections of this article to figure out what would be the safe way to load data in your case. Maybe it is SetParametersAsync
or OnParametersSetAsync
这篇关于加载组件加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!