Blazor未处理的异常渲染组件

5

我是一个Blazor的初学者,正在制作一个简单的待办事项清单项目。当我添加任务清单时出现了一个错误。 未处理异常呈现组件: 对象引用未设置为对象实例。

System.NullReferenceException: 对象引用未设置为对象实例。 at FrontEnd.Pages.Index.AddList(KeyboardEventArgs e) in C:\Users\bryan\source\repos\Productivity_App\FrontEnd\Pages\Index.razor.cs:line 20 at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)

我尝试搜索这个问题并找到了一个类似的帖子,但回答没有帮助到我,从问题上看,我认为它与Blazor的生命周期有关。以下是与此错误相关的代码。

Index.razor:

<div class="toDoList">
    @if (ToDoListCollection != null)
    {
        @foreach (string toDoList in ToDoListCollection)
        {
            <input type="checkbox" id="checkbox">
            <label for="checkbox">@toDoList</label>
            <hr />
        }
    }
    else {}
</div>

Index.razor.cs

public partial class Index
{
    public bool IsCompleted { get; set; }
    public string Description { get; set; }
    public List<string> ToDoListCollection { get; set; }
    
    public void AddList(KeyboardEventArgs e)
    {
        if (e.Key == "Enter" && !string.IsNullOrWhiteSpace(Description) || e.Key == "NumpadEnter" && !string.IsNullOrWhiteSpace(Description))
        {
            ToDoListCollection.Add($"{Description}"); // This is the line that the error message is referencing 
            Description = null;
        } 
        else {}
    }

}

集合已初始化吗?在您提供的代码中,我没有看到任何类似于ToDoListCollection = new List<string>()的内容。 - Nijenhof
这个回答解决了你的问题吗?什么是NullReferenceException,我该如何修复它?(https://dev59.com/O2445IYBdhLWcg3w3N6z) - Timothy G.
1个回答

6
我假设你的ToDoListCollection值为null,因为它没有被初始化。
将默认值分配给你的集合。
public List<string> ToDoListCollection { get; set; } = new List<string>();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接