Blazor组件未刷新



所以我有一个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()行有时间刷新之前就已经在导航了,因此它永远不会刷新。如果是这种情况,我应该如何实施?

删除StateHasChanged((,您可以从/登录";至"/&";。true应该像f5一样强制加载cookie。

NavManager.NavigateTo("/",true);

相关内容

  • 没有找到相关文章

最新更新