问题
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:
- When the component is prerendered statically.
- 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