购物车开发问题:localStorage存储数据无法正常渲染显示
购物车渲染问题:无法读取data.js字段返回undefined
开发购物车项目时遇到以下问题:
- 希望在cart.html中渲染localStorage存储的数据详情,但运行代码时无法读取data.js中的
.name等字段,返回undefined或异常图片 - 控制台能看到购物车中的完整数据(如id、name、desc等)
- 空购物车/非空购物车的判断逻辑正常,仅内容渲染失败
恳请提供修正方案与指导。
cart.html 部分代码
<div id="label" class="text-center"></div> <div id="shopping-cart" class="shopping-cart"></div> </body> <script src="src/data.js"></script> <script src="src/cart.js"></script> </html>
cart.js 代码
let label = document.getElementById('label'); let shoppingCart = document.getElementById('shopping-cart'); let basket = JSON.parse(localStorage.getItem("data")) || []; let calculation = () => { let cartIcon = document.getElementById("cartAmount"); cartIcon.innerHTML = basket.map((x) => x.item).reduce((x, y) => x + y, 0); }; calculation(); let generateCartItems = () => { if (basket.length !== 0) { return (shoppingCart.innerHTML = basket .map((x) => { console.log(x); let { id, item } = x; let search = shopItemsData.find((y) => y.id === id) || []; return ` <div class="cart-item"> <h2>${search.name} has been added</h2> </div> `; }) .join('')); } else { shoppingCart.innerHTML = ; label.innerHTML = ` <h2>Cart is EMPTY!</h2><br> <a href="index.html"> <button type="button" class="btn btn-danger">Back to Home!</button> </a> `; } }; generateCartItems();
data.js 代码
let shopItemsData = [ { id: "1", name: "Silver Wash", price: 499, desc: "This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.", img: "images/silver.jpg" }, { id: "2", name: "Gold Wash", price: 999, desc: "This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.", img: "images/gold1.jpg" }];
index.html 示例代码
<div class="shop" id="shop"> <div id=product-id-1 class="card mb-3"> <div class="row g-0"> <div class="col-md-4"> <img src="images/silver.jpg" class="img-fluid rounded-start" alt="..."> </div> <div class="col-md-8"> <div class="card-body"> <h5 class="card-title">Silver Wash</h5> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer. </p> <br> <button type="button" onclick="add(1)" class="btn btn-primary">@499 | Add to cart</button> </div> </div> </div> </div> </div>
问题根源与修正方案
1. 类型不匹配导致查找失败
shopItemsData中的id是字符串类型(如"1"),但add()方法传入的id是数字类型(比如1),存入localStorage后,y.id === id的全等判断会返回false,导致search找不到对应数据,最终返回undefined。
修正:
统一id类型,在查找时将id转为字符串:
let search = shopItemsData.find((y) => y.id === String(id)) || {};
2. 兜底值错误
当前用|| []作为查找失败的兜底,数组没有.name属性,会直接返回undefined。应改为空对象兜底,同时添加默认值避免显示异常:
let search = shopItemsData.find((y) => y.id === String(id)) || {}; // 渲染时增加默认值 return ` <div class="cart-item"> <h2>${search.name || '未知商品'} has been added</h2> </div> `;
3. 语法错误导致代码中断
else分支中shoppingCart.innerHTML = ;是无效语法,会触发报错中断执行,修改为:
shoppingCart.innerHTML = '';
4. 验证localStorage数据结构
确认localStorage中data的每个元素都包含id字段,且格式为{id: "1", item: 1}这类结构,若id字段缺失或类型错误,也会导致查找失败。
内容的提问来源于stack exchange,提问作者Dhruv Giri
相关产品推荐
相关产品推荐

