如何使用ES6+解构修复Prefer destructuring ESLint错误?
解决ESLint "Prefer destructuring" 错误的ES6+解构方案
嘿,我来帮你搞定这个解构问题!你的calculateTotal函数里,ESLint提示的"Prefer destructuring"错误,是因为你通过链式访问basketItem.product.price和basketItem.quantity,而没有直接用解构语法提取所需属性。我们可以通过嵌套解构一步到位解决这个问题,而且代码会更简洁。
先看你原来的代码:
const calculateTotal = (items) => { return items.reduce((totalPrice, basketItem) => { const price = basketItem.product.price; const quantity = basketItem.quantity; const total = price * quantity; return totalPrice + total; }, 0); };
第一步:在reduce回调参数中直接解构
我们可以在reduce的回调函数参数里,直接从basketItem中解构出quantity,以及嵌套在product里的price。写法如下:
const calculateTotal = (items) => { return items.reduce((totalPrice, { quantity, product: { price } }) => { const total = price * quantity; return totalPrice + total; }, 0); };
这里的{ quantity, product: { price } }就是关键:
quantity直接对应basketItem.quantityproduct: { price }是嵌套解构,把basketItem.product.price提取为变量price
第二步(可选):进一步简化代码
既然解构后变量直接可用,我们可以把计算逻辑直接放进return里,省去中间变量total:
const calculateTotal = (items) => { return items.reduce((totalPrice, { quantity, product: { price } }) => { return totalPrice + price * quantity; }, 0); };
甚至可以写成更简洁的一行箭头函数:
const calculateTotal = (items) => items.reduce((totalPrice, { quantity, product: { price } }) => totalPrice + price * quantity, 0);
纠正你之前的错误写法
你提到的const { basketItem: quantity } = quantity;是不正确的,这种写法是把quantity对象里的basketItem属性赋值给变量quantity,完全搞反了。正确的单属性解构应该是const { quantity } = basketItem;,而嵌套属性则是const { product: { price } } = basketItem;,我们把这两个合并到回调参数里,就完美解决了ESLint的提示。
内容的提问来源于stack exchange,提问作者The Walrus
相关产品推荐
相关产品推荐

