![](/img/trans.png)
[英]Blazor Server-Side variable doesn't update after function call because of OnAfterRenderAsync
[英]Blazor CascadingParameter won't update layout when I call it from a function, after an onclick event
我正在嘗試使用布局中的 CascadingParameter 以通用方式管理我網站的“加載”。
但是,在調用“onclick”加載之后,我無法從“繼承頁面”EditForm 的“OnValidSubmit”函數中停止“加載”。
讓我給你看。
在我的 MainLayout 中,我設法顯示正在加載的 h2 或頁面的內容,無論它是什么:
<CascadingValue Value="this">
@if (load == true)
{
<h2>Loading...</h2>
} else
{
@Body
}
</CascadingValue>
@code
{
public bool load = false;
//---------------------------
// Setters
public void Loading()
{
load = true;
}
public void StopLoading()
{
load = false;
}
}
在從該 MainLayout 繼承的其他頁面中,我有一個 EditForm 將檢查用戶名和密碼是否與數據庫匹配。
如果沒有錯誤,則應調用“加載”函數,然后在數據庫中進行搜索,然后導航到主頁。
因此,我將“加載”功能添加到我的 EditForm 的“onclick”中,當我單擊按鈕時,它會正確顯示加載 h2:
<EditForm Model="@user" OnValidSubmit="@TriggerLogin">
<InputText id="name" placeholder="Email" @bind-Value="user.Username" inputmode="email" />
<InputText id="password" placeholder="Mot de passe" @bind-Value="user.Password" type="password" inputmode="text" />
<button class="button-pink" type="submit" @onclick="Layout.Loading">Se connecter</button>
</EditForm>
然后使用我的“OnValidSubmit”函數在數據庫中進行研究:
private async Task TriggerLogin()
{
if (members.Login(user) == true)
{
// Do stuff with accesstoken
Layout.StopLoading();
NavigationManager.NavigateTo("/commandes");
}
else
{
Layout.StopLoading();
error = "Wrong password or username";
}
}
但是我的 StopLoading() 函數沒有更新我的頁面!
即使我的調試器說我在布局中正確輸入了函數,布局也不會輸入 html 部分的“else”,也不會顯示“@Body”。
我試圖在布局中使用 this.StateHasChanged() (它唯一工作的地方)但我正在尋找另一個解決方案,因為它不會顯示錯誤消息。
我該怎么做才能強制布局刷新 html 部分? 謝謝
通常失敗的重載可以通過使用StateHasChanged();
來解決StateHasChanged();
所以試試
public void StopLoading()
{
load = false;
InvokeAsync(StateHasChanged);
}
- - 編輯 - -
如果這使局部變量丟失,則可以選擇將這些變量移動到服務中。 在我的示例中,我僅針對加載和錯誤執行此操作,但可以像加載一樣完成其余操作。
public class LoadService {
public bool Load {get;set;}
public String ErrorMessage {get;set;}
}
然后改變你的代碼:
@inject LoadService LoadService
//... html part
@if (LoadService.Load== true)
{
<h2>Loading...</h2>
}
//... html part
@code
{
//... html part
public void StopLoading()
{
LoadService.Load = false;
InvokeAsync(StateHasChanged);
}
}
設置錯誤信息:
private async Task TriggerLogin()
{
if (members.Login(user) == true)
{
// Do stuff with accesstoken
Layout.StopLoading();
NavigationManager.NavigateTo("/commandes");
}
else
{
Layout.StopLoading();
LoadService.ErrorMessage = "Wrong password or username";
}
}
不要忘記在 Program.cs 中注冊服務
builder.Services.AddSingleton<LoadService>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.