【发布时间】:2021-04-20 11:03:55
【问题描述】:
我有一个博客网站,其中 cmets 在名为 CommentList 的 Component 中进行管理。
index.razor
...
Counting comments: @CommentCount
<CommentList PostId="@CurrentPost.Id" OnCommentCountChanged="OnCommentCountChangedHandler" />
@code {
...
int CommentCount;
public void OnCommentCountChangedHandler(int count)
{
CommentCount = count;
}
}
现在是组件:
CommentList.razor
[Parameter] public int PostId { get; set; }
[Parameter] public EventCallback<int> OnCommentCountChanged { get; set; }
[Inject] ICommentService CommentService { get; set; }
List<Comment> AllComments { get; set; }
bool flag;
protected override async Task OnParametersSetAsync()
{
if (PostId && !flag)
{
flag = true;
AllComments = await CommentService.GetComments(PostId);
await CountComments();
}
}
protected async Task CountComments()
{
Console.WriteLine("CountComments called");
if (AllComments == null) return;
var count = AllComments.Count();
await OnCommentCountChanged.InvokeAsync(count);
}
正如您在上面的代码中看到的,在我的组件中,我通过服务检索了这篇文章的所有 cmets,然后我调用了一个方法来通知父级计数。
我需要在检索到 cmets 列表后立即将计数传达给父级。我找到的唯一重新计算此计数 (CountingComments) 的地方是 OnParametersSetAsync。
你会注意到我使用了一个标志。没有这个标志,就会有一个永无止境的循环:
- 从
OnParametersSetAsync呼叫CountingComments - 从
CountingComments调用OnCommentCountChanged - 此“调用”会产生对
OnParametersSetAsync的调用 - 等等……
有了标志,就可以避免循环,但我想知道这是否是最好的方法?
很遗憾,无法区分每个参数的变化。如果我们有 2 或 3 个参数,如果其中一个参数发生更改,则触发方法 OnParametersSetAsync,但我们不知道涉及哪个参数。此外,对EventCallback Parameter OnCommentCountChanged 的调用也会触发此OnParametersSetAsync,但对此没有兴趣(在我的情况下)。
【问题讨论】:
-
为什么 OnInitializedAsync 不起作用?它被调用一次。
-
因为我的服务应该首先以 Id 作为参数进行获取,并且在 OnParameterSetAsync 中检索此参数。我不认为 OnInitializedAsync 中已经设置了 Id 参数。
标签: blazor blazor-webassembly blazor-client-side