Todo项目加载LocalStorage数据到UI时出现forEach空值读取错误求助
Todo列表LocalStorage同步UI时出现「Cannot read properties of null (reading 'forEach')」错误解决
我正在开发Todo列表项目,在将LocalStorage中存储的数据同步到UI界面时,遇到了「Cannot read properties of null (reading 'forEach')」错误。控制台显示错误与forEach直接相关,但LocalStorage中的值并非null,却仍触发该错误。
以下是我的代码:
const form = document.querySelector("#todo-form"); const todoInput = document.querySelector("#todo"); const todoList = document.querySelector(".list-group"); const firstCard = document.querySelectorAll(".card-body")[0]; const secondCard = document.querySelectorAll(".card-body")[1]; const filter = document.querySelector("#filter"); const clearButton = document.querySelector("#clear-todos"); eventListeners(); function eventListeners() { form.addEventListener("submit", addTodo); document.addEventListener("DOMContentLoaded", loadAllTodosToUI); } function loadAllTodosToUI() { let todos = getTodosFromStorage(); todos.forEach(function (todo) { addTodoToUI(todo) }); } function addTodo(e) { const newTodo = todoInput.value.trim(); if (newTodo === "") { showAlert("danger", "bir todo gir"); } else { addTodoToUI(newTodo); addTodoToStorage(newTodo); showAlert("success", "başarıyla eklendi"); } e.preventDefault(); } function getTodosFromStorage() { let todos; if (localStorage.getItem("todos") === null) { todos = []; } else { todos = JSON.parse(localStorage.getItem(todos)); } return todos; } function addTodoToStorage(newTodo) { let todos = getTodosFromStorage(); todos.push(newTodo); localStorage.setItem("todos", JSON.stringify(todos)); } function showAlert(type, message) { const alert = document.createElement("div"); alert.className = `alert alert-${type}`; alert.textContent = message; firstCard.appendChild(alert); setTimeout(() => { alert.remove(); }, 1000); } function addTodoToUI(newTodo) { const listItem = document.createElement("li"); const link = document.createElement("a"); link.href = "#"; link.className = "delete-item"; link.innerHTML = "<i class = 'fa fa-remove'></i>"; listItem.className = "list-group-item d-flex justify-content-between"; listItem.appendChild(document.createTextNode(newTodo)); listItem.appendChild(link); todoList.appendChild(listItem); todoInput.value = ""; }
错误原因
问题出在getTodosFromStorage函数的这一行:
todos = JSON.parse(localStorage.getItem(todos));
这里错误地将变量todos作为参数传给localStorage.getItem(),但实际应该传入字符串键名"todos"。传入未初始化的变量时,localStorage.getItem(undefined)返回null,JSON.parse(null)也会返回null,导致后续调用forEach时触发报错。
修复方案
修改getTodosFromStorage函数中的错误行:
todos = JSON.parse(localStorage.getItem("todos"));
验证修复
修改后,getTodosFromStorage会正确读取LocalStorage中todos键对应的数组数据(空数组或已存储的todo列表),此时调用forEach就不会再出现错误。
内容的提问来源于stack exchange,提问作者prawlercode
相关产品推荐
相关产品推荐

