简体   繁体   中英

How can I refresh a child component from a parent component multiple times from the same method?

Right now my child component only updates once the GetLeads() method in the parent component is finished. I never see the spinner or Searching text.

Parent Component:

<SearchResultComponent  @ref="ChildComponent"></SearchResultComponent>

Code:

 protected SearchResultComponent ChildComponent;
 public int LeadsFound { get; set; }
 public void GetLeads()
 {
      ChildComponent.Refresh(true, 0);
      var leads  = _searchService.Search(searchRequest);
      LeadsFound = leads?.Count ?? 0;
      _writeFileService.WriteToFile(leads);
      ChildComponent.Refresh(false, LeadsFound);
  }

Child Component:

@code {

    public bool Searching { get; set; } = false;
    public int LeadsFound { get; set; } = 0;
    public void Refresh(bool searching, int leadsFound)
    {
        Searching = searching;
        LeadsFound = leadsFound;
        StateHasChanged();
    }
}

@if (Searching)
{
    <div>Searching...</div>
    <div>
        <img src="~/Content/searching-spinner.gif" />
    </div>
}
else
{
    <div>Leads Found: @LeadsFound</div>
}

my child component only updates once

You can make the eventhandler async. That allows you then to call Task.Delay(1) or Task.Yield() and that will effectuate the StateHasChanged().

The call form @onclick="@GetLeads" can remain the same. Note that you don't need the 2nd @ in there.

If your searchService.Search() was async then you wouldn't need Task.Yield()

 public async Task GetLeads()
 {
      ChildComponent.Refresh(true, 0);      
      await Task.Yield();  // enable the render thread to run.
      var leads  = _searchService.Search(searchRequest);
      LeadsFound = leads?.Count ?? 0;
      _writeFileService.WriteToFile(leads);
      ChildComponent.Refresh(false, LeadsFound);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM