我正在使用 MudBlazor 库开发 .net5 Blazor WebApp。我正在尝试创建一个显示某些类别和类别页面的导航菜单。但是由于可以添加新类别或添加新类别页面,因此我需要在信息更改时刷新我的组件。在OnInitializedAsync()
此调用函数时,按预期呈现导航菜单没有问题。但是,在更新它应该呈现的任何信息后再次调用它时,这个函数似乎不再做它应该做的事情,即重新呈现组件。现在,最简单的解决方案可能是我可以简单地刷新整个页面。但这不是我想要的,因为还有其他逻辑需要继续运行而不会受到页面重新加载的干扰。我的 。
@inject CategoryService categoryService
@inject CategoryPageService categoryPageService
@inherits LayoutComponentBase
<MudText Typo="Typo.h6" Class="px-4" Style="margin-bottom: 10px; margin-top: 10px; text-align:center">Categories</MudText>
<MudDivider />
<MudNavMenu Style="color:white">
@foreach (Category category in NavCategories)
{
@if(NavCategoryPages.Count > 0)
{
@foreach(CategoryPage categoryPage in NavCategoryPages)
{
@if(categoryPage.CategoryId == category.Id)
{
<MudNavGroup Title=@category.Name>
@foreach(CategoryPage categoryPage1 in NavCategoryPages.Where(c => c.CategoryId == category.Id))
{
<MudNavLink>@categoryPage1.PageName</MudNavLink>
}
</MudNavGroup>
}
else
{
<MudNavLink>@category.Name</MudNavLink>
}
}
}
}
</MudNavMenu>
@code
{
private List<Category> NavCategories = new List<Category>();
private List<CategoryPage> NavCategoryPages = new List<CategoryPage>();
protected override async Task OnInitializedAsync()
{
await GetCategoriesNav(); //Function that should grab the new information from the database
}
public async Task GetCategoriesNav()
{
NavCategories = await categoryService.GetCategories();
NavCategoryPages = await categoryPageService.GetCategoryPages();
//This delay is to have enough time to view if the StateHasChanged has any effect on first call.
await Task.Delay(5000);
StateHasChanged();
}
}
我已经仔细检查了它们必须显示的所有值,并在调试中相应地显示出来。如果您需要任何额外的信息,请不要犹豫。
第一个电话是在:
- 类别选择器.razor
protected override async Task OnInitializedAsync()
{
await GetCategoriesNav();
}
此调用按预期呈现 NavMenu。之后,唯一一次在其他地方调用它是在我编辑/添加类别时。这是在:
- 类别管理
//These 2 functions are called via a button.
async Task AddCategory()
{
Category thisCategory = new();
var param = new DialogParameters { ["category"] = thisCategory };
IDialogReference dialog = DialogService.Show<CategoryDialog>("Add Category", param);
DialogResult result = await dialog.Result;
if(!result.Cancelled)
{
GetCategories();
//if a category has succesfully been added, it calls the same method which also gets called in the "OnInitializedAsync()"
await GetCategoriesNav();
}
}
async Task EditCategory(Category category)
{
category = await categoryService.EditCategory(category);
var param = new DialogParameters { ["category"] = category };
var dialog = DialogService.Show<CategoryDialog>("Edit Category", param);
DialogResult result = await dialog.Result;
if (!result.Cancelled)
{
GetCategories();
//if a category has succesfully been edited, it calls the same method which also gets called in the "OnInitializedAsync()"
await GetCategoriesNav();
}
}
这是唯一被调用的外部位置,但 CategoryAdministration 继承自 Category 选择器。