StateHasChanged在调用Action时也不呈现组件



我正试图在单击按钮时触发StateHasChanged。这是通过将StateHasChanged添加到event Action来完成的。调试时,我可以看到事件的Invoke方法正在被激发,但UI没有重新呈现。

这就是我想要的流程:

  1. OgToolbar.razor.cs中单击该按钮
  2. 事件被触发
  3. StorageManagerService更改本地存储器中的状态并调用事件
  4. 用户界面在OgSidebar.razor.cs中重新呈现

OgSidebar.razor.cs,其中UI必须重新渲染

protected override void OnInitialized()
{
StorageManagerService.OnChange += StateHasChanged;
}
protected override async Task OnInitializedAsync()
{
var containsKey = await StorageManagerService.ContainsKeyAsync("isSidebarToggled");
if (containsKey == false)
await StorageManagerService.SetItemAsync("isSidebarToggled", true);
_isSidebarToggled = await StorageManagerService.GetItemByKeyAsync<bool> 
("isSidebarToggled");
}
public void Dispose()
{
StorageManagerService.OnChange -= StateHasChanged;
}

OgToolbar.razor.cs,单击该按钮并触发事件

[Inject]
private IStorageManagerService StorageManagerService { get; set; }
private bool _isSidebarToggled = false;
protected override void OnInitialized()
{
StorageManagerService.OnChange += StateHasChanged;
}
protected override async Task OnInitializedAsync()
{
var containsKey = await StorageManagerService.ContainsKeyAsync("isSidebarToggled");
if (containsKey == false)
await StorageManagerService.SetItemAsync("isSidebarToggled", true);
_isSidebarToggled = await StorageManagerService.GetItemByKeyAsync<bool>("isSidebarToggled");
}
public void Dispose()
{
StorageManagerService.OnChange -= StateHasChanged;
}

StorageManagerService.cs,其中使用Blazored:在本地存储中管理状态

private readonly ILocalStorageService _localStorageService;
public event Action OnChange;
public async Task<T> GetItemByKeyAsync<T>(string identifier)
{
var itemFromLocalStorage = await _localStorageService.GetItemAsync<T>(identifier);
return itemFromLocalStorage;
}
public async Task<bool> ContainsKeyAsync(string identifier)
{
return await _localStorageService.ContainKeyAsync(identifier);
}
public async Task SetItemAsync<T>(string identifier,T item)
{
await _localStorageService.SetItemAsync(identifier, item);
OnChange.Invoke();
}

您触发了事件,但_isSidebarToggled的状态不会刷新。

大致:

//OgSidebar.razor.cs
protected override void OnInitialized()
{
StorageManagerService.OnChange += async () => 
{ 
_isSidebarToggled = await StorageManagerService
.GetItemByKeyAsync<bool> ("isSidebarToggled");
StateHasChanged ();
};
}

使用async void作为事件处理程序有点不确定。

相关内容

  • 没有找到相关文章

最新更新