简体   繁体   English

StateHasChanged 是重新渲染所有组件还是仅重新渲染差异?

[英]Does StateHasChanged re-render all the component or only the differences?

I am learning Blazor Component and I am wondering about StateHasChanged force the component to re-render all itself or only the differences.我正在学习 Blazor 组件,我想知道 StateHasChanged 会强制组件重新呈现所有自身还是仅重新呈现差异。 The intellisense report that智能感知报告指出

Notifies the component that its state has changed.通知组件其状态已更改。 When applicable, this will cause the component to be re-rendered.如果适用,这将导致重新渲染组件。

What it means with "this will cause the component to be re-rendered"? “这将导致组件被重新渲染”是什么意思?

StateHasChanged will cause only the differences to be re-rendered. StateHasChanged 只会导致重新渲染差异。

To prove that, I've created the following Blazor component that has 2 buttons:为了证明这一点,我创建了以下具有 2 个按钮的 Blazor 组件:

  • first button generates a list of 10 000 <li> elements, numbered 0 .. 9999第一个按钮生成一个包含 10 000 个<li>元素的列表,编号为 0 .. 9999
  • second button modifies the value of the first <li> and calls StateHasChanged()第二个按钮修改第一个<li>的值并调用 StateHasChanged()

Here is the complete code:这是完整的代码:

@page "/BigDataStateHasChanged"

<h3>BigDataStateHasChanged</h3>

<button class="btn btn-primary" @onclick="GenerateBigData">Generate big data</button>
<button class="btn btn-primary" @onclick="ChangeOneRow">Change 1 row</button>

@if(list != null)
{
    @foreach(var item in list)
    {
        <li>@item</li>
    }
}

@code {
    List<int> list;
    const int cMaxNumbers = 10000;

    protected void GenerateBigData()
    {
        list = new List<int>(cMaxNumbers);
        for(int i = 0; i < cMaxNumbers; i++)
        {
            list.Add(i);
        }
    }

    protected void ChangeOneRow()
    {
        list[0] = 123456;
        StateHasChanged();
    }
}


I then used the Chrome's development tools to monitor the websockets.然后我使用 Chrome 的开发工具来监控 websockets。 On the Network tab, when clicking on the first button, I can see that 1.4 MB was transferred via the websockets to the client:在 Network 选项卡上,单击第一个按钮时,我可以看到 1.4 MB 通过 websockets 传输到客户端:

在此处输入图片说明

Then, after clicking the second button that only changes the first element, I can see that only 153 bytes have been transferred:然后,单击仅更改第一个元素的第二个按钮后,我可以看到仅传输了 153 个字节:

在此处输入图片说明

So, from this, the conclusion is that only the "diff" gets rendered.因此,由此得出的结论是,只有“差异”才会被渲染。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM