Loading data on component load

拟墨画扇 提交于 2021-01-01 08:14:58

问题


One would think this is an easy task. But how do I call a service method on component load without it firing twice?

Currently -

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();
  }
}

回答1:


OnInitializedAsync lifecycle method for initializing the component is executed twice:

  1. When the component is prerendered statically.
  2. After the server connection has been established.

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



来源:https://stackoverflow.com/questions/60401430/loading-data-on-component-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!