Blazor Unhandled异常渲染组件
Blazor Unhandled exception rendering component
我是 Blazor 的初学者,正在制作一个简单的待办事项列表项目。添加列表时出现错误。
未处理的异常呈现组件: 未将对象引用设置为对象的实例。
System.NullReferenceException: Object reference not set to an instance of an object.
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)
我尝试搜索问题并找到了类似的 post 但答案对我一点帮助都没有,看着这个问题。我认为它与修复它的 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
namespace FrontEnd.Pages
{
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
有空值,因为它没有被初始化。
为您的collection分配一个默认值。
public List<string> ToDoListCollection { get; set; } = new List<string>();
我是 Blazor 的初学者,正在制作一个简单的待办事项列表项目。添加列表时出现错误。 未处理的异常呈现组件: 未将对象引用设置为对象的实例。
System.NullReferenceException: Object reference not set to an instance of an object.
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)
我尝试搜索问题并找到了类似的 post
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
namespace FrontEnd.Pages
{
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
有空值,因为它没有被初始化。
为您的collection分配一个默认值。
public List<string> ToDoListCollection { get; set; } = new List<string>();