英文:
Can't populate Blazor component from parent call
问题
我要创建一个 "Repository" Blazor 组件,并在调用方法时填充该组件。你能解释为什么这段代码不起作用吗?
当从父组件/页面调用 Load() 方法时:
<Repository @ref="repo" />
...
repo.Load();
<h3>Repository</h3>
@if (Elements == null)
{
}
else
{
<span>@Elements.Count 个元素</span>
<ul class="list-group">
@foreach (var element in Elements)
{
<li class="list-group-item">@element</li>
}
</ul>
}
@code {
protected List<string>? Elements { get; set; }
public async Task Load()
{
Elements = await Task<List<string>>.Run(() =>
{
List<string> liste = new();
liste.Add("a1");
liste.Add("b1");
liste.Add("c1");
return liste;
});
}
}
注意:我已经将你的代码翻译成中文,代码部分不做翻译。
英文:
I want to create a "Repository" blazor component and populate this component when a clla a method.
Can you explain why this code is not working ?
when the method Load() is called from a parent component/page
<Repository @ref="repo"/>
...
repo.Load();
<h3>Repository</h3>
@if(Elements==null)
{
} else
{
<span>@Elements.Count elements</span>
<ul class="list-group">
@foreach (var element in Elements)
{
<li class="list-group-item">@element</li>
}
</ul>
}
@code {
protected List<string>? Elements { get; set; }
public async Task Load()
{
Elements = await Task<List<string>>.Run(() =>
{
List<string> liste = new();
liste.Add("a1");
liste.Add("b1");
liste.Add("c1");
return liste;
});
}
}
答案1
得分: 3
你可以在 Load()
方法的最后一行添加 await InvokeAsync(StateHasChanged);
,这样可以将渲染请求放入队列中,因为你的 Load()
方法已经是一个 async Task
。
英文:
Your call to repo.Load()
is not triggering a render, likely because it's outside the component lifecycle. You can place a render request on the queue using StateHasChanged
. Since your Load()
method is already an async Task
, I would recommend adding await InvokeAsync(StateHasChanged);
as the very last line in that method.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论