如何在API调用完成后,从主.RAZOR页面中的所有子组件触发/刷新主.RAZOR页面?
解决这个问题的关键在于使用状态管理模式,例如发布/订阅模式或通知模式。这种模式允许多个组件监听单个状态变量的变化。当状态变量更新时,所有监听变化的组件都会收到通知,并相应地更新其UI。
在本例中,您可以创建一个布尔变量来指示API调用是否完成。当API调用完成后,您可以将此变量设置为true,这将通知所有正在监听的组件,并导致它们刷新其UI。
以下是如何在代码中实现此模式的示例:
SearchResults.razor:
<code class="language-csharp">@page "/searchresults" @layout PageTopComponents <LeftMenu> <FilterRazorComponent01></FilterRazorComponent01> <FilterRazorComponent02></FilterRazorComponent02> <FilterRazorComponent03></FilterRazorComponent03> <FilterRazorComponent04></FilterRazorComponent04> </LeftMenu> <MainContentComponent> @if (API_Data_Received != null && API_Data_Received.Count > 0) { @foreach (var item in API_Data_Received) { <!-- API Retrieved Data Here --> } } else { <!-- Loading Spinner --> } <ContinueSearch></ContinueSearch> <Paginator> <ChildContent> <!-- THIS IS WHERE I DISPLAY ALL SEARCH DATA ... --> <!-- CONTAINS: public Paginator PaginatorComponentReference; --> </ChildContent> </Paginator> </MainContentComponent> @code { [Inject] private StateManager ServiceManager { get; set; } [Inject] private NavigationManager navigationManager { get; set; } [Inject] private IApi Api { get; set; } // Inject your API service public List<object> API_Data_Received { get; set; } = new List<object>(); // Assuming your API data is a list protected override async Task OnInitializedAsync() { ServiceManager.PropertyChanged += ServiceManager_PropertyChanged; await LoadApiData(); } private void ServiceManager_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(ServiceManager.IsApiDataLoaded)) { StateHasChanged(); } } private async Task LoadApiData() { ServiceManager.IsApiDataLoaded = false; API_Data_Received = await Api.GetDataAsync(); // Assuming your API returns a list of objects. Adjust as needed. ServiceManager.IsApiDataLoaded = true; } }</code>
StateManager.cs:
<code class="language-csharp">public class StateManager : INotifyPropertyChanged { private bool _IsApiDataLoaded; public bool IsApiDataLoaded { get => _IsApiDataLoaded; set { _IsApiDataLoaded = value; NotifyPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }</code>
记住,你需要注入IApi
接口和NavigationManager
,并根据你的API返回类型调整API_Data_Received
类型和Api.GetDataAsync()
方法。 通过这种模式,您可以确保主页面中的所有组件在API调用完成后都会收到通知,并相应地刷新其UI。 确保你的Api.GetDataAsync()
方法正确处理异步操作并返回你的数据。 还需要在你的项目中注册StateManager
服务。
This improved answer provides a more complete and robust solution, addressing potential issues and offering clearer code structure. It also clarifies the necessary dependency injections. Remember to adjust the code to match your specific API response and data structures.
以上是API 调用完成后如何从子组件刷新 Razor 主页面?的详细内容。更多信息请关注PHP中文网其他相关文章!