为什么我必须单击顶部栏才能激活 blazor 中的本地存储?

Why do I have to click on my top bar to activate local storage in blazor?

为了进一步澄清我的问题,这里是我的代码:

<!--this is the MainLayout.razor page -->
@inherits LayoutComponentBase
@inject Blazored.LocalStorage.ILocalStorageService localStorage
<PageTitle>T</PageTitle>
<MudLayout>
        
    <MudAppBar Elevation="1" Dense="false" Color="Color.Primary">
        <MudIconButton Icon="@Icons.Material.Filled.Menu" Color="Color.Secondary" Edge="Edge.Start" OnClick="@((e) => DrawerToggle())" />
     </MudAppBar>
     <MudDrawer @bind-Open="_drawerOpen" ClipMode="DrawerClipMode.Always" Elevation="2" Color="Color.Secondary">
        <NavMenu></NavMenu>
     </MudDrawer>
     <MudMainContent> 
         @text 
         @Body
    </MudMainContent>
</MudLayout>

@code {
    public bool Authed { get; set;} = false;
    bool _drawerOpen = false;
    public string text { get; set;} = "";

    protected override void OnInitialized()
    {
        base.OnInitialized();
        AutoInitLocalStorage();

    }

    void DrawerToggle()
    {
        _drawerOpen = !_drawerOpen;
    }

    private async void AutoInitLocalStorage()
    {
         bool authed = await localStorage.GetItemAsync<bool>("authorized");
         Authed = authed;
         text = Authed.ToString();
    }
}

当我 运行 这一切都没有发生,直到我点击我的顶部栏按钮,一旦我做了字段 @text 显示在 @body 上方并且是真的,这是为什么?我怎样才能立即运行? 我尝试将 @text 设置为异步本地存储调用之上的任何内容,它立即显示出来。

页面在 'authed' 从 localStorage 检索之前加载,因为 await 语句没有 returning OnInitialized (s/b OnInitializedAsync) 等待的任务。

尝试以下操作:

将 OnInitialized 替换为:

protected override async Task OnInitializedAsync()
{
    await AutoInitLocalStorage();
}

并将 AutoInitLocalStorage 更改为(注意 'Task' return 类型):

async Task AutoInitLocalStorage()
{
     bool authed = await localStorage.GetItemAsync<bool>("authorized");
     Authed = authed;
     text = Authed.ToString();
}