Blazor,如果加载则从渲染返回/停止渲染

Mac*_*kan 4 c# blazor blazor-server-side

我们在所有 Blazor 页面中都有如下类似的代码,用于简单地停止渲染直到加载完成。它似乎工作正常,但该网站尚未进行太多测试。

我有点担心这个,意味着回归在页面中间,会/可能会以一种或另一种方式扰乱 Blazors 流程,导致内存泄漏或其他问题。

我看到的每个示例都使用 if/else 代替,但如果下面的示例有效,那么最好减少页面的嵌套和复杂性。

那么,这个方法好用吗,还是会给我们带来麻烦呢?

一个简化的例子:

@usings/injects here
    
@if (IsLoading)
{
    @:Loading content..
    return;
}
    
<p>This will not be rendered until page is initialized and Model populated</p> 
<p>@Foo.Bar</p>
    
@code {
    public bool IsLoading { get; set; } = true;
    public FooModel Foo { get; set;}
    
    protected override async Task OnInitializedAsync()
    {
        try
        {
            Foo = await GetFooFromRepo();
        }
        catch (Exception ex)
        {
            Toaster.Add("Something went wrong when loading foo.", 
                 MatToastType.Danger, "Error");
        }
        finally
        {
            IsLoading = false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

StP*_*lis 5

我不会使用这种方法,

我建议使用@if-else语句来执行此操作,如下所示:

@if (IsLoading)
{
    @:Loading content..
}
else 
{  
  <p>This will not be rendered until page is initialized and Model populated</p> 
  <p>@Foo.Bar</p>
}
    
Run Code Online (Sandbox Code Playgroud)