简体   繁体   English

Object 参考未设置为 Blazor WebAssembly 中的 Object

[英]Object Reference Not set to an Object in Blazor WebAssembly

I am building an E-Commerce website to display my wife's crochet projects on using Blazor in Dotnet 6. Now, the website is functioning just fine, but it pops up a message that an unhandled error has occurred every time the Nav bar is loaded.我正在建立一个电子商务网站,以显示我妻子在 Dotnet 6 中使用 Blazor 的钩针项目。现在,该网站运行良好,但每次加载导航栏时都会弹出一条消息,提示出现未处理的错误。 The error is as follows:错误如下:

crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
   at MermaidCraftsFE.Client.Shared.NavMenu.BuildRenderTree(RenderTreeBuilder __builder) in C:\Users\scull\source\repos\MermaidCraftsFE\MermaidCraftsFE\Client\Shared\NavMenu.razor:line 19
   at Microsoft.AspNetCore.Components.ComponentBase.<.ctor>b__6_0(RenderTreeBuilder builder)
   at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment, Exception& renderFragmentException)

The code indicated by the error is here:错误指示的代码在这里:

@foreach (var category in categoryService.Categories)
        {
            <div class="nav-item px-3">
                <NavLink class="nav-link" href="@category.Url">
                    @category.Name
                </NavLink>
            </div>
        }

And the Category Service code which is necessary is here:必要的类别服务代码在这里:

public async Task GetCategoriesAsync()
        {
            var response = await _httpClient.GetFromJsonAsync<ServiceResponse<List<Category>>>("api/Category");
            if (response != null && response.Data != null)
            {
                Categories = response.Data;
            }
        }

What am I missing that is causing this error?我错过了什么导致此错误? Demonstration is in a week from today and I would like for this error box to not pop up when the function is behaving as expected.从今天开始的一周内进行演示,我希望当 function 的行为符合预期时,不会弹出此错误框。 I have tried changing the "var" in "var category in categoryService.Categories" to Category, but the error pops up all the same.我尝试将“categoryService.Categories 中的var category”中的“var”更改为Category,但仍然弹出错误。

what happens if response comes back as null here?如果响应在这里返回为 null 会发生什么? var response = await _httpClient.GetFromJsonAsync<ServiceResponse<List<Category>>>("api/Category");

With how your logic is set up, you might need to add an empty list of categories in that case.根据您的逻辑设置方式,在这种情况下,您可能需要添加一个空的类别列表。 Something like:就像是:

    if (response != null && response.Data != null)
        {
            Categories = response.Data;
        }
    else{
       Categories = new List<Categories>();
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM