reactjs - 对反应中的循环感到困惑
问题描述
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循环中只输出一次。
解决方案
我如何解决它?
更改第二个变量名
为什么?
在你的 React 环境中,你很可能使用像 Babel 这样的 JS 编译器。Babel 将获取您的代码并使其在大多数浏览器中可运行,您必须摆脱它,const
并且let
由于某些浏览器不支持它们,babel 会为您执行此操作并将它们替换为var
.
有什么不同?const
andlet
是块作用域,但是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)
推荐阅读
- java - 当我在 Java 中使用 jaxb 时,如何使用 gradle 将我的自定义注释添加到生成的类中?
- spring - 获取 yaml 文件而不是 application.properties
- go - 如何在 Golang 中的并发代码中使用 defer
- django - 从文件 Django-Rest_Framework 序列化许多对象的问题
- macos - 访问被拒绝尝试连接到 TFS 服务器
- javascript - 在 Bing 地图上放置图钉首先可以正常工作,然后我不能再放置并且我的鼠标停止工作。但我看不出有什么不对?
- r - dplyr 过滤器或带有两个输入的 [ ]
- reinforcement-learning - openai 旋转中的 RL PPO 动作空间裁剪
- javascript - 在具有结构的js中循环变量
- pymssql - pymssql 中的主键复制处理