对于循环反应感到困惑

时间:2018-11-15 04:19:57

标签: reactjs loops for-loop

componentDidMount() {
    for (let i = 0; i < 3; i++) {
        let i = 'not a number'
        console.log(i)  // output only one time
    }
}

componentDidMount() {
    let i = 5 // add one line...
    for (let i = 0; i < 3; i++) {
        let i = 'not a number'
        console.log(i)  // output three times
    }
}

请注意,输出时间,如果直接在浏览器中运行这些循环,则这两个代码将输出3次,但在React中,在for循环中仅输出1次。

1 个答案:

答案 0 :(得分:2)

如何解决?

更改第二个变量名称

为什么?

在您的React环境中,您最有可能使用像Babel这样的JS编译器。 Babel将使用您的代码并使之在大多数浏览器中可运行,因此您必须摆脱constlet,因为某些浏览器不支持它们,babel会替您这样做并替换为var

有什么区别? constlet受块限制,而var受函数限制。因此,您的变量i被提升(移动)到“函数”的顶部,并由所有人共享。 constlet处于块范围内,因此它们仅在各自的范围内可见,i循环的初始化程序中声明的for可以被初始化程序看到,并且代码,但如果在跟随块中声明另一个变量i,它们将变成两个不同的变量,例如:

for (let i = 0; i < 3; i++) {
  // they act like two different variables and are independent of each other
  let g = 'not a number'
  console.log(g)
}
// 1: i = 0, g (inner i) = 'not a number'
// 2: i = 1, g (inner i) = 'not a number'
// 3: i = 2, g (inner i) = 'not a number'

React被编译成这样的东西

// variable i gets hoisted to the top
var i;
for (i = 0; i < 3; i++) {
  i = 'not a number'
  console.log(i)
}
// 1: i = 0
// 2: i = 'not a number' ('not a number' < 3 is false)