我正试图在单击按钮时触发StateHasChanged。这是通过将StateHasChanged
添加到event Action
来完成的。调试时,我可以看到事件的Invoke
方法正在被激发,但UI没有重新呈现。
这就是我想要的流程:
- 在
OgToolbar.razor.cs
中单击该按钮 - 事件被触发
StorageManagerService
更改本地存储器中的状态并调用事件- 用户界面在
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
作为事件处理程序有点不确定。