How does the Blazor WeatherForecast sample work?

ぃ、小莉子 提交于 2019-12-06 14:11:43

When you await a method ( OnInitAsync ), you yield control to the calling code, which continue to execute the rest of the code, rendering your component with the text "Loading...". When the Asynchronous method returns, that is, the task is completed, and new parameters are to be set, your control must be re-rendered to reflect the new changes. And of course the if-else statement runs once again, yielding a different result.

This actually has nothing to do with Blazor. This is how Asynchronous programming works in C#. However, the code in the ComponentBase class checks this conditions and decides when to re-render the component by calling the StateHasChanged method.

See ComponentBase.SetParameters and ComponentBase.ContinueAfterLifecycleTask to understand it better: https://github.com/aspnet/AspNetCore/blob/343208331d9ebbb3a67880133f4139bee2cb1c71/src/Components/src/Microsoft.AspNetCore.Components/ComponentBase.cs

Hope this helps...

The if check is on null:

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
     //table here
}

And the loading of the data is asynchronous. So when the page inits, the forecasts are null. Now the loading starts (async) and when that is finished it will populate the forecasts array. That will make it non-null and display the table.

Async is the key here I guess..

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