当使用Blazor中的路由参数时,经常需要在OnInitializedAsync生命周期方法中初始化组件。但是,当路由参数更改时,组件不会自动重新初始化。因此,我们需要在OnParametersSetAsync方法中手动重置路由参数。
以下是一个示例组件,演示如何在OnParametersSetAsync方法中重置路由参数:
@page "/mycomponent/{id}"
@inject NavigationManager NavigationManager
@Title
@code {
private int _id;
private string _title;
[Parameter]
public int Id
{
get => _id;
set
{
if (_id != value)
{
_id = value;
}
}
}
public string Title => _title;
protected override async Task OnInitializedAsync()
{
await LoadData(_id);
}
protected override async Task OnParametersSetAsync()
{
await LoadData(_id);
}
private async Task LoadData(int id)
{
// Do some data loading based on the current route id
// ...
_title = "Loaded data for id " + id;
}
// Reset the id and re-run OnInitializedAsync when navigating to this component
protected override async Task OnNavigatedToAsync(NavigationEventArgs args)
{
if (args.Uri != null)
{
var uri = new Uri(args.Uri);
if (int.TryParse(uri.Segments.Last(), out _id))
{
await OnInitializedAsync();
}
}
}
}
在这个示例中,我们重写了OnNavigatedToAsync方法来获取当前路由参数并重新初始化组件。我们还重写了Id属性的set方法,确保仅在参数发生更改时才重新初始化路由参数。这允许组件更快地响应路由参数更改,并减少了不必要的初始化。