在Blazor中,正确的方法是如何将级联参数值从父组件传递给子组件/孙子组件?

3
我是Blazor的新手(dotnet 8 rc2),想知道为什么像TeamStandings这样的子组件可以加载空的CascadingParameter currentSeason?
DataLayout:
@if (currentSeason!=null && currentSeason.ActiveCategory.IsActive)
{
    <CascadingValue Value="@currentSeason">          
        @Body
    </CascadingValue>
}
@code {
   
    [CascadingParameter]
    RouteData RouteData { get; set; }
    public string? Slug { get; set; }
    public CurrentSeasonModel? currentSeason { get; set; } = new();
    protected override async Task OnInitializedAsync()
    {
        if (RouteData.RouteValues.TryGetValue("Slug", out var slug) == true)
        {
           // update currentSeason
        }
     }

}

父页面:
@page "/abc"
    @if (currentSeason != null && currentSeason.ActiveCategory.IsActive)
    {
    
        <TTSWeb.Blazor.Client.Pages.League.RecentFixtures />
        <TTSWeb.Blazor.Client.Pages.League.TeamStandings  />
     
    }
    @code {
     
        [CascadingParameter]
        public CurrentSeasonModel? currentSeason { get; set; }
    }

在TeamStandings组件上: 输入图像描述

这是 Blazor 8,你的组件都是相同的渲染类型还是有混合的? - undefined
@BrianParker 对于这个页面,父页面位于主项目中,就像上面的信息一样。对于来自客户端的组件,它们都是InteractiveAuto。对于其他页面,我有客户端组件与不同的渲染类型混合在一起。 - undefined
1个回答

2
如果你没有设置它,那么它就是空的。这就是错误的提示。你还没有展示`TeamStandings`,所以其他的都只是猜测。
你有两个解决方案:
1. 在定义它的地方将`[CascadingParameter]`设置为一个值。 2. 在尝试使用它之前,将`[CascadingParameter]`设置为一个值。 3. 在进行任何渲染之前测试它是否被设置,并且如果为空则抛出错误。
<h3>MyComponent</h3>

@code {
    // This sets it to default - which is null bit we tell the compiler that we know better
    [CascadingParameter] private string Value { get; set; } = default!;

    public override Task SetParametersAsync(ParameterView parameters)
    {
        parameters.SetParameterProperties(parameters);

        // Before we do any rendering check to make sure that Value is set and throw an exception if it's not
        // This will only normally occur during Development
        ArgumentNullException.ThrowIfNull(Value);

        return base.SetParametersAsync(ParameterView.Empty);
    }
}

附加信息

我刚刚注意到你在TeamStandings中的级联声明

[CascadingParameter] CurrentSeasonModel currentSeason { get; set; }

你的级联值的类型是CurrentSeasonModel?
不同的类型:一个是可空的,另一个不是!甚至还有绿色的警告[我也错过了!]。

谢谢,但我已经在DataLayout上更新了CascadingParameter。所有组件都应该从这个布局继承级联参数,对吗? - undefined
请查看有关不同类型的更新评论。 - undefined
这并没有改变任何事情,还是一样的。起初我使用了相同的类型,只是尝试了不同的类型,看看是否能强制绑定值不为空。 - undefined
没有看到更多的代码,我没有更多的建议。它是可以工作的,所以你肯定是做错了什么。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接