我的页面上有以下代码:
@if (players == null)
{
<p><em>Loading...</em></p>
}
else
{
<p>Number of Players: @players.Count</p>
<p>Number of Teams: @teamsCount</p>
<p>Excess Players: @excessPlayers</p>
}
@code {
private List<PlayerModel> players;
private int teamsCount { get; set; }
private int excessPlayers { get; set; }
protected override async Task OnInitializedAsync()
{
players = await _db.GetPlayers();
int teamsCount = players.Count / 5;
int excessPlayers = players.Count % 5;
}
加载的html会正确显示一段时间,然后players.Count
会正确更新并显示41,但是teamsCount
和excessPlayers
始终显示0。
我尝试在StateHasChanged()
的结尾处致电OnInitializedAsync()
。
我还尝试了在单独的方法中设置teamsCount
和excessPlayers
并调用StateHasChanged()
的方法,但这两个都不起作用。 teamsCount
和excessPlayers
仍然保持显示为0,尽管我在代码中看到它们分别是8和1,这是正确的。
我在做什么错了?
答案 0 :(得分:2)
您正在通过teamsCount
方法为excessPlayers
和OnInitializedAsync
创建新的局部变量:
protected override async Task OnInitializedAsync()
{
players = await _db.GetPlayers();
int teamsCount = players.Count / 5;
int excessPlayers = players.Count % 5;
}
您应该改为设置属性的值:
protected override async Task OnInitializedAsync()
{
players = await _db.GetPlayers();
teamsCount = players.Count / 5;
excessPlayers = players.Count % 5;
}