javascript - JS文件中React Component类之外的代码什么时候运行?

标签 javascript reactjs react-native

假设我有一个 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
}

问题

  1. 'a'的声明和值设置代码什么时候运行?当其他文件导入/需要此文件时它是否运行?

  2. 我可以在这个文件中有一些标志并且不时更改,然后从许多其他文件中读取这个标志的值吗? (像单例管理器?)如果可以,我该如何导出和导入?

  3. 创建多个文件究竟意味着什么? (除了它将大块代码分成小块以提高可读性之外)它还有其他区别吗?

最佳答案

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.jsc.js 都导入了它。另请参阅它是如何导出和导入的,以及当它更改时如何在其他模块中获取更改。

关于javascript - JS文件中React Component类之外的代码什么时候运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58212381/

相关文章:

ios - 为什么react-native应用程序在热重载时会重新启动(在热重载模式下保存的更改)?

react-native - 如何修复 React-Native 错误 'could not unzip gradle-5.4.1-all.zip'

javascript - 文本颜色相对于其后面的图像

javascript - Dart : capture an image of a Flutter webview

javascript - 返回新数组的对象数组之间的差异

reactjs - 如何使用 Semantic UI API 发出 json 内容类型的 POST 请求

javascript - 即使条件不满足,if 条件也会被执行

javascript - 整体选择按钮

javascript - 关闭选项卡时不调用useEffect清理函数

react-native - react native 抽屉导航 : Drawer not closing when pressing an overlay