javascript - 导致eslint no-shadow错误的解构参数

标签 javascript ecmascript-6 eslint destructuring

我的理解是这样的解构将从传入的参数对象中挑选属性:

const last = "Smith" // unrelated const

const full = function({ first, last }) {
  return [first, last].filter(v => v).join(" ")
}

full({last: "Doe"}) // "Doe"
full({}) // ""

这似乎对导入同​​样有效。

import last from "last"; // unrelated import

export function full({ first, last }) {
  return [first, last].filter(v => v).join(" ")
}

full({last: "Doe"}) // "Doe"
full({}) // ""

为什么这会导致 no-shadow错误?

error 'last' is already declared in the upper scope no-shadow

是否存在full 可以访问外部引用的情况?无权利?如何在不重命名不相关的外部 last 引用的情况下使语法接近于此?

最佳答案

它导致 eslint 错误,因为 last 在导入和函数中声明为参数。所以在函数内部,参数 last 隐藏了导入 last。您只需更改函数内参数的名称或关闭 eslint。

import last from "last"; // unrelated import

export function full({ first, last: lst }) {
  return [first, lst].filter(v => v).join(" ")
}

full({last: "Doe"}) // "Doe"
full({}) // ""

……或者……

import last from "last"; // unrelated import

export function full({ first, last }) { // eslint-disable-line no-shadow
  return [first, last].filter(v => v).join(" ")
}

full({last: "Doe"}) // "Doe"
full({}) // ""

关于javascript - 导致eslint no-shadow错误的解构参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44445100/

相关文章:

reactjs - 为什么 React 钩子(Hook)可以有条件地与 throw 错误一起使用?

javascript - 在 React 中使用类名、ID 和数据属性时的最佳实践是什么

javascript - 在页面加载之前使用 jQuery 定位图像

javascript - 基于 Javascript 中的过滤器数组的过滤器数组

javascript - 经典继承与原型(prototype)继承的区别

javascript - 如何在 IntelliJ 的事件日志窗口中显示完整的 WebStorm 信息?

javascript - Eslint 不允许内置全局函数?

javascript - 条件渲染react-redux

javascript - 向特定设备发送通知

javascript - ES6 : self-import vs ordering exports for referencing