简体   繁体   English

在声明之前在 function 组件内使用全局 const 变量

[英]Using a global const variable inside a function component before its declaration

I came across this code, but I do not understand why the const variable myList can be used inside the function component before its declaration.我遇到了这段代码,但我不明白为什么在声明之前可以在 function 组件内部使用 const 变量 myList。

  export default function ListComponent(props) {
    const listItems = myList.map((item) => <li>{item}</li>);
   return <ul>{listItems}</ul>;
}
const myList = ["apple", "orange", "strawberry", "blueberry", "avocado"];

but the following code throws an error.但以下代码会引发错误。 It is because let or const variable cannot be used before it is declared (Variables defined with let and const are hoisted to the top of the block, but not initialized.).这是因为 let 或 const 变量在声明之前不能使用(用 let 和 const 定义的变量被提升到块的顶部,但未初始化。)。

error: Uncaught ReferenceError: Cannot access 'a' before initialization错误:未捕获的 ReferenceError:在初始化之前无法访问“a”

const b=2;
 function test() {
  console.log(a);
  console.log(b);
}
test();
const a=1;

Can anyone explain how the first code works?谁能解释第一个代码是如何工作的? Thanks in advance!提前致谢!

ListComponent runs after myList has been initialized since you use it in an export and the declaration happens before the function is called. ListComponent 在 myList 初始化之后运行,因为您在导出中使用它并且声明发生在调用 function 之前。

Also, there is an exception when using variables declared via "var".此外,使用通过“var”声明的变量时也会出现异常。 Then all declarations are moved to the top of the current scope and initialized.然后将所有声明移到当前 scope 的顶部并初始化。 You can read up more on hoisting here您可以在此处阅读有关吊装的更多信息

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

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