【问题标题】:Why do I have to click on my top bar to activate local storage in blazor?为什么我必须单击顶部栏才能激活 blazor 中的本地存储?
【发布时间】:2022-01-01 17:32:07
【问题描述】:

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

<!--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 设置为异步本地存储调用之上的任何内容,它会立即显示出来。

【问题讨论】:

    标签: c# blazor-server-side


    【解决方案1】:

    在从 localStorage 检索“已验证”之前加载页面,因为 await 语句没有返回 OnInitialized (s/b OnInitializedAsync) 等待的任务。

    尝试以下方法:

    将 OnInitialized 替换为:

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

    并将 AutoInitLocalStorage 更改为(注意“任务”返回类型):

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-27
      • 2021-12-30
      • 2021-01-29
      • 2014-02-15
      • 1970-01-01
      相关资源
      最近更新 更多