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

Blazor中HTTP Get请求触发两次重渲染的原因及解决咨询

Blazor中HTTP请求触发两次重渲染的原因及解决方法

原因分析

Blazor的异步事件处理机制默认会触发两次重渲染:

  1. 当异步方法执行到await关键字时,方法暂停并返回未完成的Task,框架会自动调用StateHasChanged()触发一次重渲染——这是框架为了及时响应UI交互(比如按钮点击后的状态反馈)设计的默认行为。但你的代码中这次重渲染前没有修改任何状态,所以不会产生UI变化,但重渲染过程确实发生了。
  2. HTTP请求完成后,方法继续执行并修改currentCount,状态变更会再次触发StateHasChanged(),导致第二次重渲染,此时UI会更新计数并显示test区块。

解决方法

要阻止第一次无意义的重渲染,可以通过重写ShouldRender方法控制渲染时机:

修改后的完整代码

@page "/counter"
@inject HttpClient _http
<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@if(currentCount > 0)
{
    <div>test</div>
}

@code {
    private int currentCount = 0;
    private bool _isLoading = false;

    protected override bool ShouldRender()
    {
        // 加载期间阻止重渲染
        if (_isLoading)
            return false;
        return base.ShouldRender();
    }

    private async Task IncrementCount()
    {
        _isLoading = true;
        // 执行HTTP请求,此时ShouldRender返回false,不会触发重渲染
        var json = await _http.GetStringAsync(_http.BaseAddress + "trust/hasTrust?CaseID=4");
      
        _isLoading = false;
        currentCount++;
        // 状态变更后,ShouldRender返回true,触发一次重渲染
    }
}

原理说明

  • 通过_isLoading标记异步操作状态:请求开始时设为true,请求完成后设为false。
  • 重写ShouldRender方法,当_isLoading为true时返回false,阻止框架在await阶段触发的无意义重渲染;请求完成后恢复正常渲染逻辑,仅在状态变更时触发一次重渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 10:35:24