When does the code outside React Component class in a JS file run?

Hua*_*Hua 2 javascript reactjs react-native

Say I have a JS file contains 2 React Component class definition and a bunch of other things:

// 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
}
Run Code Online (Sandbox Code Playgroud)

Questions

  1. When will the declaration and value setting code for 'a' run? Does it run when this file is imported/required by other files?

  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?

  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?

acd*_*ior 6

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?

Runs the first time the file is imported. It is not executed on subsequential imports.

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?

You can.

Exporting:

export let a = 0;
Run Code Online (Sandbox Code Playgroud)

Importing:

import { a } from './filename.js';
Run Code Online (Sandbox Code Playgroud)

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?

  • Breaks code into small chunks;
  • Allows reuse; and
  • Enables encapsulation of non-exported variables/functions.

--

Check a demo of modules usage: http://plnkr.co/edit/0ImgQj2KzLj9O1D63Gq9?p=preview

注意 howa.js只加载一次,即使它是由b.js和导入的c.js。还可以查看它是如何导出和导入的,以及在它发生变化时如何在其他模块中获取更改。

  • 是的,它会运行,否则模块加载器将不知道该文件实际导出了该组件。 (2认同)
  • 关于从“b.js”更改“a.stuff”,您确实不能,因为导入会在导入器的范围内创建常量标识符。如果您尝试更改它,您应该会收到错误(只是不知道此错误是否在所有浏览器和节点中标准化)。 (2认同)