【问题标题】:const scope with babel transpiler [duplicate]带有 babel 转译器的 const 范围 [重复]
【发布时间】:2023-03-17 14:15:01
【问题描述】:

我在我的 reducer 中构建了一个 react-redux 应用程序我在使用 babel es2015 和 stage-2 用 webpack 编译我的 bundle.js 后遇到了这个错误,我做了一些研究,它假设它们的 const 范围是块代码,所以为什么我收到双重声明错误? 我的减速器就像上面的这个函数

function print(foo){
  switch(foo){
    case 'test':
      const bar = 2;
      console.log(bar+1);
      break;
    case 'test1':
      const bar = 1;
      console.log(bar+2);
      break;
    default:
      console.log('no match')
      break;
  }
}
print('test');

【问题讨论】:

  • 那么,您的代码中哪里有 { } 块?

标签: ecmascript-6 redux babeljs


【解决方案1】:

你需要像这样用花括号包裹每个 case 分支:

function print(foo){
  switch(foo){
    case 'test': {
      const bar = 2;
      console.log(bar+1);
      break;
    }
    case 'test1': {
      const bar = 1;
      console.log(bar+2);
      break;
    }
  }
}

switch 语句中的所有内容都是一个块作用域。大括号将每个 case 置于其自己的块范围内——没有它们,您将在同一范围内重新声明一个 const,这将出错。

【讨论】:

    猜你喜欢
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 2019-05-01
    • 2017-10-13
    相关资源
    最近更新 更多