Blazor未处理异常渲染组件



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

系统。NullReferenceException:对象引用没有设置为对象的实例。在FrontEnd.Pages.Index。AddList(KeyboardEventArgs e) in c: users brain sourcereposProductivity_AppFrontEndPagesIndex.razor.cs:第20行在System.Reflection.RuntimeMethodInfo。调用(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具有空值,因为它没有初始化。

为集合指定一个默认值。

public List<string> ToDoListCollection { get; set; } = new List<string>();

最新更新