blazor 为什么登录后我什么也看不到?

blazor why after login i see nothing?

我还在学习 blazor 但有一些基本的可能问题 谁能告诉我为什么我看到登录屏幕,登录后我只看到没有内容的白屏?

主要布局:

@inherits LayoutComponentBase
@inject UserService u

@if (u.User != null)
{

<div class="page">
    <div class="sidebar">
        <NavMenu />
    </div>

    <main>
        <article class="content px-4">
            @Body

        </article>
    </main>
</div>
}
else
{
   <LoginComponent></LoginComponent>
}

并且登录组件是一个表单并且带有登录方法 与

@inject UserService us

并在提交时:

private LoginModel model = new LoginModel();

private  void OnValidSubmit()
{

    try
    {
        us.LoginUser(model);
        StateHasChanged();          
    }
    catch (Exception ex)
    {
        StateHasChanged();
    }
}

并且 userservice 注册为 singelton

 builder.Services.AddSingleton<UserService>();

现在很简单就像

   public class UserService
{
    public UserModel User ;


    public  void LoginUser(LoginModel model)
    {
        if (model.Username=="xxx")
        {               
            this.User = new UserModel();
            this.User.UserName = model.Username;
            this.User.SurName = "asd'";                             
        }
    }
}

非常感谢和问候!

您的代码

us.LoginUser(model);
StateHasChanged();

在子组件中调用,因此对父组件刷新没有影响。

@if (u.User != null)

不会自动刷新。

您可以在 UserService 中声明一个事件,例如:

public class UserService
{
    public UserModel User ;

    public EventHandler OnUserLoggedIn;

    public  void LoginUser(LoginModel model)
    {
        if (model.Username=="xxx")
        {               
            this.User = new UserModel();
            this.User.UserName = model.Username;
            this.User.SurName = "asd'";
            OnUserLoggedIn?.(this, null);
        }
    }
}

然后在您的 MainLayout 中添加:

@code
{
    protected override void OnInitialize()
    {
        u.OnUserLoggedIn += (_, __) => this.StateHasChanged();
    }
}

这样,登录操作将在 MainLayout 上调用 StateHasChanged()。 没有 运行 代码,所以可能有一些小的近似值。