我有一个 Razor 页面,它依赖于其父类和第二个子类,第二个子类有自己的类并从其父类接收数据,我的问题是在第二次调用 API 时,数据没有传递给第二个子类,在其父类更改数据时第二个子类不会被渲染,但在第一次渲染时它可以正常工作并传递数据。
Parent.razor
@inherits ParentBase;
<FirstChild/>
<SecondChild data="@data"/>
FirstChild.razor
@inherits ParentBase;
// call its parent method
<span @onclick='(() => callApi())'/>
ParentBase.cs
public class ParentBase : ComponentBase
{
public Data data { get; set; }
protected override async Task OnInitializedAsync()
{
data = await Services.GetData();
}
// call from a child
public void callApi
{
data = await Services.GetData();
}
}
SecondChild.razor
<Table data="@data"/>
SecondChildBase.cs
public class SecondChildBase : ComponentBase
{
[Parameter]
public Data data { get; set; }
protected override void OnParametersSet()
{
// this is not getting called
StateHasChanged();
Console.WriteLine(data);
}
}
CascadingValue
或创建类似于“服务”的东西。如果你想了解更多信息,请阅读这篇文章。 - Vencovsky