【问题标题】:Blazor - Avoid OnInitialized/OnInitializedAsyncBlazor - 避免 OnInitialized/OnInitializedAsync
【发布时间】:2021-10-21 22:38:56
【问题描述】:

我在 Blazor 中制作了两个在按下按钮时会切换的组件,如下所示:

<div class="row full-height">
   <div class="col-md-12">
      @if (condition)
      {
         <Component1 Parameter="foo"> 
         </Component1>
      }
      else
      {
         <Component2 Parameter="bar"></Component2>
      }
   </div>
</div>

当其中一个组件重新呈现时,它会再次执行 OnInitialized 和 OnInitializedAsync。 我想知道是否有一种方法可以只在这些方法中执行一次代码。

非常感谢!

【问题讨论】:

    标签: c# asp.net-core blazor


    【解决方案1】:

    您的问题是每次切换时您都在删除组件并将其添加到 RenderTree。

    改为在每个组件上使用简单的Show 参数。现在,组件仅在 Index 首次渲染时才添加到 RenderTree。

    下面的快速演示:

    组件 1

    @if (this.Show)
    {
    <h3>Component1</h3>
    <div>Rendered at : @rendertime</div>
    }
    
    @code {
    
        [Parameter] public bool Show { get; set; }
    
        string rendertime;
    
            protected override void OnInitialized()
            {
            rendertime = DateTime.Now.ToLongTimeString();
                base.OnInitialized();
            }
    
    }
    

    组件 2

    @if (this.Show)
    {
    <h3>Component2</h3>
    <div>Rendered at : @rendertime</div>
    }
    
    @code {
    
        [Parameter] public bool Show { get; set; }
    
        string rendertime;
    
            protected override void OnInitialized()
            {
            rendertime = DateTime.Now.ToLongTimeString();
                base.OnInitialized();
            }
    
    }
    

    index.razor

    @page "/"
    @using StackOverflow.Answers.Components
    
    <Component1 Show="_show1"/>
    
    <Component2 Show="_show2"/>
    
    <div class="m-2 p-2">
        <button class="btn btn-dark" @onclick="ShowComponent1"> Toggle 1</button>
        <button class="btn btn-secondary ms-2" @onclick="ShowComponent2"> Toggle 2</button>
        <button class="btn btn-primary ms-2" @onclick="Toggle"> Toggle</button>
    </div>
    
    @code {
    
        bool _show1;
        bool _show2;
    
        void ShowComponent1()
        {
            _show1 = !_show1;
        }
    
        void ShowComponent2()
        {
            _show2 = !_show2;
        }
    
        void Toggle()
        {
            if (_show2)
            {
                _show2 = false;
                _show1 = true;
            }
            else
            {
                _show2 = true;
                _show1 = false;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-12
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 2022-08-23
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多