首页 > 解决方案 > 对反应中的循环感到困惑

问题描述

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循环中只输出一次。

标签: reactjsloopsfor-loop

解决方案


我如何解决它?

更改第二个变量名

为什么?

在你的 React 环境中,你很可能使用像 Babel 这样的 JS 编译器。Babel 将获取您的代码并使其在大多数浏览器中可运行,您必须摆脱它,const并且let由于某些浏览器不支持它们,babel 会为您执行此操作并将它们替换为var.

有什么不同?constandlet是块作用域,但是var函数作用域。因此,您的变量i会被提升(移动)到“函数”的顶部并由所有人共享。const并且let是块范围的,因此它们仅对各自的范围可见,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) 

推荐阅读