You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor异步级联值始终为null,寻求异步加载解决方案

解决方案

你的核心问题是级联值的类型不匹配,同时没正确处理异步加载的时机。下面提供两种可行的异步实现方案:


方案1:级联异步委托,在子组件中主动调用获取值

你在MainLayout里级联的是Func<Task<string>>类型的异步委托,但Index中声明的是string类型参数,类型不匹配导致无法获取值。调整代码如下:

MainLayout.razor

<CascadingValue Value="@(async () => await someclass.GetValueAsync())" Name="asyncValue">
  <article class="content px-4">
    @Body
  </article>
</CascadingValue>

Index.razor

<h1>Hello! @AsyncValue</h1>

@code{
    [CascadingParameter(Name = "asyncValue")] 
    public Func<Task<string>> GetAsyncValue { get; set; }

    private string AsyncValue { get; set; }

    protected override async Task OnInitializedAsync()
    {
        if (GetAsyncValue != null)
        {
            AsyncValue = await GetAsyncValue();
            // 此处可正常使用AsyncValue
        }
    }
}

方案2:在MainLayout中先完成异步加载,再渲染子组件

如果希望子组件直接拿到加载完成的字符串,而非委托,可以在布局层先完成异步获取,等待值就绪后再渲染级联内容:

MainLayout.razor

@if (_asyncValue != null)
{
    <CascadingValue Value="@_asyncValue" Name="asyncValue">
        <article class="content px-4">
            @Body
        </article>
    </CascadingValue>
}
else
{
    <p>加载中...</p>
}

@code{
    private string _asyncValue;

    protected override async Task OnInitializedAsync()
    {
        _asyncValue = await someclass.GetValueAsync();
    }
}

Index.razor

<h1>Hello! @AsyncValue</h1>

@code{
    [CascadingParameter(Name = "asyncValue")] 
    public string AsyncValue { get; set; }

    protected override async Task OnInitializedAsync()
    {
        // 此时AsyncValue已为加载完成的值,可直接使用
    }
}

两种方案的区别:

  • 方案1允许子组件自主控制异步加载时机,适合延迟加载或按需加载场景
  • 方案2会先在布局层完成加载,子组件初始化时就能拿到就绪的值,适合需要确保值已加载再渲染子组件的场景

内容的提问来源于stack exchange,提问作者EyeSeeSharp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 16:50:23