微软文档ASP.NET Core Razor 组件生命周期,中文都认识,意思不是太明白,故做了一些测试。
OnInitialized与OnInitializedAsync
@page "/"
@foreach (var item in Items)
{
@item
<hr />
}
@code {
List<int> Items = default!;
protected override void OnInitialized()
{
Items = Enumerable.Range(0, 10).ToList();
}
}
能正确运行
- 运行 OnInitialized
- 运行 @foreach
@page "/"
@foreach (var item in Items)
{
@item
<hr />
}
@code {
List<int> Items = default!;
protected override async Task OnInitializedAsync()
{
Items = Enumerable.Range(0, 10).ToList();
await Task.Delay(1);
//do Something
}
}
也能正确运行
- 运行 OnInitializedAsync 到await ...
- 运行 @foreach
- 运行 OnInitializedAsync 的do something
@page "/"
@foreach (var item in Items)
{
@item
<hr />
}
@code {
List<int> Items = default!;
protected override async Task OnInitializedAsync()
{
await Task.Delay(1);
Items = Enumerable.Range(0, 10).ToList();
}
}
出错了,@foreach语句Items为空
- 运行 OnInitializedAsync 到await ...
- 运行 @foreach,Items尚未赋值,出错
所以,异步的写法必须如下:
@page "/"
@if (Items is not null)
{
foreach (var item in Items)
{
@item
<hr />
}
}
@code {
List<int> Items = default!;
protected override async Task OnInitializedAsync()
{
await Task.Delay(1);
Items = Enumerable.Range(0, 10).ToList();
}
}
标签:生命周期,Items,await,OnInitializedAsync,item,Task,foreach,Blazor,随笔
From: https://www.cnblogs.com/catzhou/p/18093990