繁体   English   中英

对于循环反应感到困惑

[英]Confused for loop in react

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次,但作为响应,在for循环中仅输出1次。

我如何解决它?

更改第二个变量名称

为什么?

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

有什么不同? constlet是块作用域的,而var是函数作用域的。 因此, i将您的变量提升(移动)到“函数”的顶部,并由所有人共享。 constlet是块作用域的,因此它们仅在各自的作用域内可见,在for循环的初始化程序中声明的i可以被初始化程序和后面的代码块看到,但是如果在follow块中声明另一个变量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) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM