我的页面中有以下代码:
@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。
我试着在OnInitializedAsync()
结束时呼叫StateHasChanged()
。
我还尝试在一个单独的方法中设置teamsCount
和excessPlayers
,并调用StateHasChanged()
,但都不起作用。teamsCount
和excessPlayers
仍然显示为0,尽管我可以在代码中看到它们分别是8和1,这是正确的。
我做错了什么?
您正在OnInitializedAsync
方法中为teamsCount
和excessPlayers
创建新的局部变量:
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;
}