我计划的设计是有4个按钮的主页。当用户单击这些按钮中的任何一个时,它将向导航中添加一个项目。我使用这个单例来管理状态
public class StateManager
{
public event Action NewPlanAdded;
public void AddPlan()
{
NewPlanAdded?.Invoke();
}
}
我把这个单例注入了子组件
@inject StateManager StateManager
<button class="btn btn-primary" @onclick="CreateNewPlan">Create New Plan</button>
@code {
private void CreateNewPlan()
{
StateManager.AddPlan();
}
}
和导航组件
@inject StateManager StateManager
<div class="@NavMenuCssClass" @onclick="ToggleNavMenu">
<ul class="nav flex-column">
@foreach (var item in Items)
{
<li class="nav-item px-3">
<NavLink class="nav-link" href="@item.Item1" >
<span class="@item.Item2" aria-hidden="true"></span> @item.Item3
</NavLink>
</li>
}
</ul>
</div>
@code {
IList<Tuple<string, string, string>> Items { get; set; }
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
StateManager.NewPlanAdded += NewPlanAdded;
Items = new List<Tuple<string, string, string>>
{
new Tuple<string, string, string>("", "oi oi-home", "Home")
};
}
public void Dispose()
{
StateManager.NewPlanAdded -= NewPlanAdded;
}
private void NewPlanAdded()
{
Items.Add(new Tuple<string, string, string>("plan", "oi oi-plus", "Plan (unsaved)"));
}
}
问题是新的列表项直到导航组件被隐藏后才出现,然后再次显示。如何在集合更改时刷新foreach ?
你应该通知你的组件状态已经改变执行InvokeAsync(StateHasChanged)
:
private void NewPlanAdded()
{
Items.Add(new Tuple<string, string, string>("plan", "oi oi-plus", "Plan (unsaved)"));
InvokeAsync(StateHasChanged); //<--- this line
}
意识到,在您的场景中,仅仅调用StateHasChanged()
是不够的,您应该从正确的线程(使用InvokeAsync
)