Blazor组件未刷新

时间:2020-09-01 14:38:14

标签: c# blazor blazor-client-side blazor-webassembly

因此,我有一个Blazor应用程序,其中用户登录,并且标题组件根据用户是否登录而变化。使用登录后,它们将被重定向到主页,但是除非单击浏览器上的“刷新”按钮,否则标题组件不会更新。我尝试使用StateHasChanged()。这是我在标头组件中的相关代码:

@using Newtonsoft.Json
@inject IJSRuntime JsRuntime
@inject NavigationManager NavManager

@if (!string.IsNullOrWhiteSpace(FirstName))
{
    <div class="header-user-widget">
        <button class="btn btn-cart">
            Cart <span class="badge badge-cart">@CartCount</span>
        </button>
        <i class="fa fa-user-circle"></i> @FirstName @LastName
        <i class="fa fa-sign-out-alt header-sign-out" @onclick="SignOutClicked"></i>
    </div>
}

@code {
    private string FirstName { get; set; }
    private string LastName { get; set; }
    private int CartCount { get; set; }

    protected override async Task OnInitializedAsync()
    {
        var page = NavManager.ToBaseRelativePath(NavManager.Uri).ToLower();
        var cookie = await JsRuntime.InvokeAsync<string>("Cookies.get", "Login");

        if (!page.StartsWith("login"))
        {
            if (string.IsNullOrWhiteSpace(cookie))
            {
                NavManager.NavigateTo("/Login");
                return;
            }
        }
        if (!string.IsNullOrWhiteSpace(cookie))
        {
            var decodedCookie = cookie.FromBase64String();

            FirstName = CookieHelper.GetValueFromKey(decodedCookie, "FirstName");
            LastName = CookieHelper.GetValueFromKey(decodedCookie, "LastName");
        }

        CartCount = await NumberOfItemsInCart();
    }
}

这是我的登录页面:

@page "/login"

@inject IJSRuntime JsRuntime
@inject NavigationManager NavManager

<LoginBox OnLoginButtonClick="@LoginButtonClicked" />

@code {

    private async Task LoginButtonClicked(LoginBoxReturnModel model)
    {
        var cookieString = $"UserId={model.UserId}|FirstName={model.FirstName}|LastName={model.LastName}|Email={model.EmailAddress}|IsAdmin={model.IsAdmin}";
        var encyptedString = cookieString.ToEncryptedBase64String();

        await JsRuntime.InvokeVoidAsync("Cookies.set", "Login", encyptedString);

        StateHasChanged(); // This line doesn't seem to have any effect
        NavManager.NavigateTo("/");
    }
}

用户登录后,他们将被正确重定向到"/"页面,但标题不会更新。如果我在浏览器中按F5刷新它,则标题正确。我感觉正在发生的事情是,应用程序正在导航,而StateHasChanged()行没有任何刷新时间,因此它永远不会刷新。如果是这样,我应该如何实施呢?

1 个答案:

答案 0 :(得分:2)

将StateHasChanged()拖放到“ /登录”到“ /”之间。 true应该像f5那样强制加载cookie。

NavManager.NavigateTo("/",true);