简体   繁体   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
    }
}

Please notice that output times, if run these loops in browser directly, both these codes will output three times, but in react, it outputs only one time in for loop. 请注意,输出时间,如果直接在浏览器中运行这些循环,则这两个代码将输出3次,但作为响应,在for循环中仅输出1次。

How do I fix it? 我如何解决它?

Change the second variable name 更改第二个变量名称

Why? 为什么?

With your React environment, you are most likely using a JS compiler like Babel. 在您的React环境中,您最有可能使用像Babel这样的JS编译器。 Babel will take your code and make it runnable in most browsers, with this you have to get rid of const and let as some browsers don't support them, babel does this for you and replaces them with var . Babel将使用您的代码并使之在大多数浏览器中可运行,因此您必须摆脱constlet某些浏览器不支持const ,babel会为您执行此操作并将其替换为var

What's the difference? 有什么不同? const and let are block scoped but var is function scoped. constlet是块作用域的,而var是函数作用域的。 So your variable i get hoisted (moved) to the top of the "function" and shared by everyone. 因此, i将您的变量提升(移动)到“函数”的顶部,并由所有人共享。 const and let are block scoped so they are only visible to their respective scopes, the i declared in the for loop's initializer can be seen by the initializer and the block of code following, but if you declare another variable i in the follow block they become two different variables like such: 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'

While React gets compiled to something like this 虽然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