集合更改时 Blazor WASM 更新导航

Blazor WASM Update Navigation when Collection Changes

我计划的设计是有一个有 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