【问题标题】:Blazor WebAssembly Lifecycle Methods when accidentally Browser refreshes浏览器意外刷新时的 Blazor WebAssembly 生命周期方法
【发布时间】:2021-06-02 09:00:53
【问题描述】:

我已经习惯了 Blazor WASM。 我有一些从自定义基类继承的页面。 在这个基类中,我有一个级联参数。

 public class CustomBlazorComponentBase : LayoutComponentBase
    {
        private bool disposedValue;

        [Inject]
        protected HttpInterceptorService Interceptor { get; set; }

        [CascadingParameter]
        protected TelerikNotification Notification { get; set; }

        protected override Task OnInitializedAsync()
        {
            Interceptor.RegisterEvent(Notification.ShowError);

            return base.OnInitializedAsync();
        }   
}

在 MainLayout.razor 中我得到了以下几行

<CascadingValue IsFixed="true" Value="@Notification">
                <div class="content px-4">
                    @Body
                </div>
</CascadingValue>            
<TelerikNotification @ref="@Notification" Class="notification"
                                 HorizontalPosition="@NotificationHorizontalPosition.Center"
                                 VerticalPosition="@NotificationVerticalPosition.Bottom" />

页面开始

@inherits ItnBlazorComponentBase 

如果出现问题,HttpInterceptor-Class 会获得一个委托来显示错误。 一切正常,符合预期。

但是当用户不小心按下浏览器的 F5 来刷新页面时,没有调用 Lifecycle-Method。不是 OnInitializedAsync,不是 OnParametersSetAsync 等等。

为什么?以及如何避免这个问题? 问题是,我的代表不会注册,因此不会显示任何通知。

谢谢!

【问题讨论】:

    标签: c# telerik blazor-webassembly


    【解决方案1】:

    经过几个小时的研究,回答了我自己的问题。它非常简单,并在 Stackoverflow 的这个问题中得到了回答

    Outermost CascadingValue is lost on page refresh or direct link

    解决方案是用布尔值包围 MainLayout.razor 中的 CascadingParameter

            @if (HasRendered)
            {
                <CascadingValue IsFixed="true" Value="@Notification">
                    <div class="content px-4">
                        @Body
                    </div>
                </CascadingValue>
            }
    

    并在 MainLayout.razor.cs 后面的代码中在第一次渲染后设置它

        protected override void OnAfterRender(bool firstRender)
        {
            if(firstRender)
            {
                HasRendered = true;
                StateHasChanged();
            }
    
            base.OnAfterRender(firstRender);
        }
    

    【讨论】:

      【解决方案2】:

      我应用了您的解决方案,但问题仍未解决,刷新页面级联参数时丢失 @if(已渲染) { @身体

              }
      

      然后我定义了 bool 变量 HasRendered 并将下面的代码粘贴到 MainLayout.razor.cs 受保护的覆盖无效 OnAfterRender(bool firstRender) { 如果(第一次渲染) { HasRendered = true; StateHasChanged(); }

          base.OnAfterRender(firstRender);
      }
      

      【讨论】:

      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2021-04-05
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-15
      相关资源
      最近更新 更多