Razor 组件 - 异步加载和显示数据

问题描述

我有一个显示文章列表的 Razor 组件,我想在页面呈现后异步加载每篇文章的图像,以便用户可以看到一个一个地在页面上弹出的图像。

问题是,我应该在哪里以及如何拨打这些电话?

HTML:

@foreach (Article article in articles)
{
   <div>
      <p>@article.name</p>
      if (article.image != null) 
      {
         <img src="data:image/jpg;base64,@article.image">
      }
   </div>
}

代码

List<Article> articles = new List<Article>();
protected override async Task OnInitializedAsync()
{
    articles = LoadArticles(); //Asume this function initialises the article list
}

async Task LoadPicture(Article article)
{
    await article.LoadImage(); //This will make the server call to get the base64 of the image
}

我需要为页面中的每篇文章调用 LoadPicture 函数,但我希望异步执行,而不必等待所有调用刷新整个页面

我应该如何进行?

解决方法

这是我在评论中描述的粗略示例,您可以执行此操作,它应该可以实现您最初想要的行为。

这样做意味着每个 Article 组件都会自行处理以及何时呈现或更新它,并且每个用于获取图像数据的 api 调用都应该是独立的。

-- 文章列表组件

@foreach(var article in Articles)
{
    <Article Model="article">
}


@code {

    List<Article> Articles {get;set;}

    protected override Task OnInitializedAsync()
    {
        return LoadArticlesAsync(); //Api call to get all articles list and which sets Articles.
    }


}

-- Article.razor 组件

@if (Model != null)
{
    <h1> @Model.Title </h1>

    @if (_imageLoaded)
    {
        <img src="@ImageBase64"/>
    }
}

@code
 {
    [Parameter]
    public Article Model {get;set;}

    private bool _imageLoaded = false;
    private string ImageBase64 {get;set;}

    protected override async Task OnInitializedAsync()
    {
        ImageBase64 = await LoadArticleImage();
        _imageLoaded = true;
    }
}