本文介绍了Blazor foreach在OnInitializedAsync调用后不呈现元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将项目列表返回到前端的服务.服务方法实现为异步/等待方法.当我从前端通过我的 OnInitializedAsync()方法调用服务时,我可以看到列表正在被填充.然后,当需要渲染页面时,项目列表"为空,并且未渲染我的组件.为什么会这样?

I have a service that returns a List of Projects to my frontend. The service method is implemented as an async/await method. When I call my service from my frontend thourgh my OnInitializedAsync() method I can see that the List is being populated. Then when the time comes to render the page the List of Projects is empty and my component is not rendered. Why is this?

@using ProjCore.Services.Interfaces

@inject IProjectService ProjectService

<div>
    @foreach (var pro in Projects)
    {
        <h2>Sanitycheck header...</h2>
        <ProjectContainer Project="pro" />
    }
</div>

@code {
    private List<ProjectModel> Projects = new List<ProjectModel>();

    protected override async Task OnInitializedAsync()
    {
        var Projects = await ProjectService.GetProjects();
    }
}

在我看来,以上所述应该可行.

In my mind the above should work.

推荐答案

首先,这不应是私有的:

First off, this should not be private:

private List<ProjectModel> Projects = new List<ProjectModel>();

将其设置为公开或受保护.其次,您将GetProjects的结果设置为局部变量,而不是html读取的Property.也许尝试类似的东西:

Set it to be public or protected. Secondly, you are setting the results from your GetProjects to a local variable and not to the Property that the html is reading from. Maybe try something like:

Projects = await ProjectService.GetProjects();

或者如果GetProjects不返回列表,则为这种形式;

or this flavor if GetProjects doesn't return a List;

Projects = await ProjectService.GetProjects().ToList();

主要,摆脱"var".您不需要StateHasChanged().

Mainly, get rid of the "var". You shouldn't need a StateHasChanged().

吉姆

这篇关于Blazor foreach在OnInitializedAsync调用后不呈现元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 17:04