每次调用 StateHasChanged 时执行一个方法

Execute a method each time StateHasChanged is called

假设我有这个 blazor 组件(我正在使用 wasm):

<p>@name</p>

@code{
  private int id;
  public void SetId(int id) // will be called by another component that has a reference to this component
  {
    this.id = id;
    StateHasChanged();
  }

  private string name;
  private async Task UpdateName()
  {
    // httpService is injected
    this.name = await httpService.Get<string>($"api/getname?id={this.id}");
  }
}

如何在每次调用 SetId(因此 StateHasChanged)时调用 UpdateName 方法?

我尝试在生命周期方法 SetParametersAsyncOnParametersSetAsync 中调用它。但是我认为每次调用 StateHasChanged 时都不会调用这些方法。可能是因为组件没有参数。

will be called by another component that has a reference to this component

那么首选的干净方法是不使用 compRef.SetId(id) 而是将 Id 作为参数传递:

 <MyComponent Id="id" />

给你的组件一个 [Parameter] public int Id {get; set; } 并从 OnParameterSetAsync()

调用 UpdateName()

另外,使用 SetId() 的简单方法。
你通常应该避免 async void 但在这种情况下它是合适的。

private int id;
public async void SetId(int id) // will be called by another component 
{
  this.id = id;

  // await so it is complete before the next line.
  await Updatename();            

  // when you know you always call it from the UI
  StateHasChanged();  

  //// or Invoke to avoid Cross-Threading issues. The await is optional.
  //await InvokeAsync(StateHasChanged);
}

调用StateHasChanged()的责任显然属于SetId()。