假设我有一个 JS 文件包含 2 个 React Component 类定义和一堆其他的东西:
// a file called OuterComponent.react.js
import xxx from xxx;
import yyy from yyy;
// When does these run?
let a = 0;
a = 1;
export default class OuterComponent extends React.PureComponent<> {
render() {
return (
<View>
<InnerComponent />
</View>
);
}
}
class InnerComponent extends React.PureComponent<> {
//... something
}
问题
'a'的声明和值设置代码什么时候运行?当其他文件导入/需要此文件时它是否运行?
我可以在这个文件中有一些标志并且不时更改,然后从许多其他文件中读取这个标志的值吗? (像单例管理器?)如果可以,我该如何导出和导入?
创建多个文件究竟意味着什么? (除了它将大块代码分成小块以提高可读性之外)它还有其他区别吗?
最佳答案
Question 1: When will the declaration and value setting code for 'a' run? Does it run when this file is imported/required by other files?
在导入文件时第一次运行。它不会在后续导入时执行。
Question 2: Can I have some flag in this file and changes from time to time, and then read the value of this flag from many other files? (like a singleton manager?) If I can, how do I export it and import it?
你可以。
导出:
export let a = 0;
导入:
import { a } from './filename.js';
Question 3: What does creating multiple files actually mean? (except that it breaks huge chunk of code into small chunks for better readability) Does it make any other difference?
- 将代码分成小块;
- 允许重用;和
- 启用非导出变量/函数的封装。
--
检查模块使用的演示:http://plnkr.co/edit/0ImgQj2KzLj9O1D63Gq9?p=preview
请注意 a.js
只加载一次,即使 b.js
和 c.js
都导入了它。另请参阅它是如何导出和导入的,以及当它更改时如何在其他模块中获取更改。
关于javascript - JS文件中React Component类之外的代码什么时候运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58212381/