Blazor WASM-使用RouteData远离布局导航会创建重复组件 [英] Blazor WASM - Navigation away from Layout using RouteData creates duplicate components
本文介绍了Blazor WASM-使用RouteData远离布局导航会创建重复组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
经过一番努力,我终于找到了我所经历的事情的根本原因。每当将RouteData作为CascadingParameter注入到布局中,然后导航到不同的布局时,Blazor将构造两个新组件,并在处置其中一个组件之前对其进行初始化。因此,在OnInitializedAsync期间提取的任何数据都将执行两次,而不会以任何方式检测到它。
有人有解决此问题的方法吗?我在他们的回购上发现了这张旧票,但看起来没有太多活动。 https://github.com/dotnet/aspnetcore/issues/20637
App.razor:
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<CascadingValue Value="@routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</CascadingValue>
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
MyLayout.razor:
@inherits LayoutComponentBase
@layout MainLayout
<a href="/someOtherPageWithoutThisLayout">Go Back</a>
@Body
@code {
[CascadingParameter] RouteData RouteData { get; set; }
}
目标组件的生命周期如下所示:
MyComponent constructed: HashCode=216708300
MyComponent OnInitializedAsync: HashCode=216708300
MyComponent constructed: HashCode=785069820
MyComponent OnInitializedAsync: HashCode=785069820
MyComponent disposing: HashCode=216708300
推荐答案
以下方法似乎可以解决此问题。它依赖于通过正文访问RouteData,而不是注入它。
protected override void OnInitialized()
{
if (Body?.Target is RouteView routeView)
{
var value = routeView.RouteData.RouteValues["routeParameterName"];
}
}
编辑1:上述方法不适用于嵌套布局。以下示例处理了这些情况。
public static bool TryGetRouteData(this Delegate renderFragment, out RouteData routeData)
{
routeData = null;
if (renderFragment?.Target is RouteView routeView)
{
routeData = routeView.RouteData;
}
else if (renderFragment?.Target is object target)
{
// the target may be a CompilerGenerated class
var bodyField = target.GetType().GetField("bodyParam");
if (bodyField is not null)
{
var value = bodyField.GetValue(target);
if (value is Delegate childDel)
{
TryGetRouteData(childDel, out routeData);
}
}
}
return routeData is not null;
}
然后在布局/组件类中:
protected override void OnInitialized()
{
if (Body?.TryGetRouteData(out var routeData) == true)
{
// stuff here
}
}
这篇关于Blazor WASM-使用RouteData远离布局导航会创建重复组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文