til
  • README
  • Software Development Roles
  • solid
  • README
    • service-worker
  • docker
    • arg
    • 更新docker版本
  • editor
    • vscode
    • Creating a VS Code Theme
  • english
    • words
  • front-end
    • ==
    • ECMAScript
    • IIFE
    • Label
    • basic
    • html.js.css渲染顺序
    • npm-vs-yarn
    • obj-delete-key-value
    • react
    • split-join-and-replace
    • video
    • 前端自检清单
    • 递归及去重
    • css
      • css换肤
      • flex
      • list
      • nth-child和nth-of-type区别
      • padding
      • position
      • 层叠上下文
      • 层叠样式(+)
      • 正方形
      • 语义化标签
    • dom
      • DOCTYPE
      • HEAD
      • 修改document
      • 自定义表单验证
    • electron
      • basic
    • es6
      • basic-type
      • basic
      • prototype-example
      • defineProperty
      • understanding-es6
        • 0.introduction
        • Appendix A: Smaller Changes
        • Appendix B: Understanding ES7
        • Block-Binding
        • Proxies&Reflection
        • class
        • 解构赋值
        • function
        • improved-array
        • iterators&generators
        • modules
        • object
        • promise
        • Map&Set
        • symbol
    • images
      • 前端角度看图片
    • interview_case
      • lexical_scope
      • redux和localstroage存储位置
    • javascript
      • fuck-the-js
      • js-engine-work
      • js原生操作dom
      • what-is-function-program
      • 执行上下文
      • articles
        • JavaScript中使用函数组合
        • JavaScript中的依赖注入
        • JavaScript作用域链中的标识符解析和闭包
        • JavaScript是何如工作的--概述
        • JavaScript深拷贝
        • JavaScript的全局变量是如何工作的
        • js继承常见的误解
        • node12&chrome中7个新的提案功能
        • 你真的懂JavaScript吗
      • date
        • index
      • engines
        • basic
        • JavaScript引擎基础:外形和内联缓存
        • v8中推测性优化的介绍
        • 优化原型
        • 更快的异步功能和promise
      • events
        • baisc
        • 事件冒泡和捕获
        • 定义事件
        • 页面生命周期
      • higher-order-function
        • curry
        • monad
      • module
        • basic
        • main&module
      • objects
        • iterator
        • spread
        • examples
          • iterator
      • performance
        • blocking-css
        • cache
      • prototype
        • Property-Descriptors
        • basic
        • prototype-shadow
      • you-dont-known-js
        • async&performance
          • Chapter 1: Asynchrony: Now & Later
          • Chapter 2: Callbacks
          • Chapter 3: Promises
          • Chapter 4: Generators
        • scope & closures
          • apA
          • apB
          • apC
          • apD
          • chapter1-what-is-scope
          • chapter2-lexical-scope
          • chapter3-function-vs-block-scope
          • chapter4-hoisting
          • chapter5-scope-closure
        • this & object prototypes
          • chapter1-this-or-that
          • chapter2-this-make-sense
          • chapter3-objects
          • chapter4-mixing(up)-class-object
          • chapter5-prototype
          • chapter6-behavior-delegation
        • types&grammer
          • Chapter1-Types
          • Chapter2-Values
          • Chapter3-Natives
          • Chapter4-coercion
          • Chapter5-grammer
        • up & going
          • chapter1-into-programming
          • chapter2-into-javascript
          • chapter3-into-YDKJS
    • mobile
      • iPhone分辨率终极指南
    • npm
      • arguments
      • build
    • react-native
      • prop-methods
    • react
      • PropTypes
      • basic
      • codebase-overview
      • component-element-instance
      • context
      • how-to-known-component-is-func-or-class
      • overview
      • react16.9
      • react18计划
      • react的设计原则
      • reconciliation
      • setState
      • useMemo
      • why-do-we-write-super-props
      • 从头实现一个react
      • concurrent
        • 引入并发模式(仅试验)
      • conf
        • conf-2019
      • events
        • 合成事件概述
      • hooks
        • custom-hook
        • effect-hook
        • hooks-api
        • intro
        • overview
        • rules
        • state-hook
        • hooks-vs-class
          • thinking-in-react-hooks
      • overreact
        • Development模式是如何工作的
        • How-Does-setState-Know-What-to-Do
        • Why-Do-React-Elements-Have-a-$$typeof-Property
        • Why-Do-React-Hooks-Rely-on-Call-Order
        • how-to-known-component-is-func-or-class
        • preparing-tach-talk-motivation
        • react作为ui运行
        • things-i-dont-known-as-2018
        • ui-element-problem-and-build-yourself
        • why-do-we-write-super-props
        • 一份完整的useEffect指南
        • 为什么X不是Hook
        • 函数组件与类有什么不同?
        • 演讲准备2-what-why-how
        • 编写弹性组件
        • 让setInterval在React-Hooks中为声明式
      • practice
        • render
      • react-dom
        • basic
      • react-redux
        • apiv7.1-hooks
        • connect
        • shallow-equal
      • redux
        • applyMiddleware
        • applyMiddleware2-细节
        • example
    • regex
      • index
    • stories
      • 数组下标
      • 阻止事件冒泡
    • svelte
      • compile-svelte-in-your-head-1
      • compiler-overview
      • parser
        • 写一个解析器-JavaScript的JSON解析器
    • turbopack
      • basic
    • typescript
      • interface和type的区别
    • webpack
      • hash
      • webpack4-for-react
      • webpack4
      • webpack4to5
      • babel
        • babel-parser和acorn的区别
        • babel.7.11
        • family
        • react16.14使用new-transform
        • update-to-7
    • pdf
      • deep-js
        • basic
      • react
        • reintroducing
  • git
    • capital
    • emoji
  • http
    • http2.0
    • response
  • rails
    • api
    • flash
    • middleware-vs-metal
    • model
    • performance
    • routes
    • environment
      • error
    • patterns
      • service
    • sidekiq
      • params
    • deploy
      • capistrano
        • ssh
  • ruby
    • self
    • net
      • http请求携带cookie
  • server
    • ss
    • ssh
    • user
    • crawler
      • puppeteer
    • nginx
      • domain-without-80
      • nginx节省带宽
  • sql
    • rails
    • search
Powered by GitBook
On this page
  1. front-end
  2. react
  3. overreact

why-do-we-write-super-props

Previousui-element-problem-and-build-yourselfNext一份完整的useEffect指南

Last updated 3 years ago

原文:

我听说最近很热。具有讽刺意味的是,我想通过描述有关类组件的有趣事实来开始这个博客。那会怎么样!

这些陷阱对于有效地使用React并不重要。但是如果你想更深入地了解事情的运作方式,你可能会发现它们很有趣。

这是第一个。

我写过的super(props)比我知道的要多:

class Checkbox extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isOn: true };
  }
  // ...
}

当然,让我们跳过仪式:

class Checkbox extends React.Component {
  state = { isOn: true };
  // ...
}

当React 0.13在2015年增加对普通类的支持时,使用这样的语法。定义构造函数和调用super(props)成为临时解决方案,直到类字段提供符合人体工程学的替代方案。

但是,让我们回到这个例子,只使用ES2015功能:

class Checkbox extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isOn: true };
  }
  // ...
}

我们为什么调用super?我们可以不调用它吗?如果我们必须调用它,如果我们不传递props会发生什么?还有其他论点吗?让我们来看看。

在JavaScript中,super指的是父类构造函数。(在我们的示例中,它指向React.Component实现。)

重要的是,在调用父构造函数之前,不能在构造函数中使用this。 JavaScript不会让你:

class Checkbox extends React.Component {
  constructor(props) {
    // 🔴 Can’t use `this` yet
    super(props);
    // ✅ Now it’s okay though
    this.state = { isOn: true };
  }
  // ...
}

有一个很好的理由说明为什么JavaScript在你触摸它之前强制执行父构造函数。考虑一个类层次结构:

class Person {
  constructor(name) {
    this.name = name;
  }
}

class PolitePerson extends Person {
  constructor(name) {
    this.greetColleagues(); // 🔴 This is disallowed, read below why
    super(name);
  }
  greetColleagues() {
    alert('Good morning folks!');
  }
}

想象一下,在允许调用super之前使用this。一个月后,我们可能会更改greetColleagues以在邮件中包含此人的姓名:

greetColleagues() {
    alert('Good morning folks!');
    alert('My name is ' + this.name + ', nice to meet you!');
}

但是我们忘记了在super调用有机会设置this.name之前调用this.greetColleagues。所以this.name甚至还没有定义!如您所见,这样的代码很难想到。

为了避免这些陷阱,JavaScript强制要求如果你想在构造函数中使用它,你必须首先调用super。让父级做自己的事!此限制也适用于定义为类的React组件:

constructor(props) {
    super(props);
    // ✅ Okay to use `this` now
    this.state = { isOn: true };
  }

这给我们留下了另一个问题:为什么要传递props?

你可能认为将props传递给super是必要的,以便基本的React.Component构造函数可以初始化this.props:

// Inside React
class Component {
  constructor(props) {
    this.props = props;
    // ...
  }
}

但不知何故,即使你没有使用props参数调用super,你仍然可以在render和其他方法中访问this.props。 (如果你不相信我,请亲自试试!)

这是如何运作的?事实证明,在调用构造函数后,React也会在实例上分配props:

// Inside React
const instance = new YourComponent(props);
instance.props = props;

因此,即使你忘记将props传递给super,React仍会在之后设置它们。这是有原因的。

那么这是否意味着你可以只写super()而不是super(props)?

尽可能不要这样,否则会使人困惑。

当然,React稍后会在你的构造函数运行后分配this.props。但是this.props在调用super和构造函数结束之间仍然是未定义的:

// Inside React
class Component {
  constructor(props) {
    this.props = props;
    // ...
  }
}

// Inside your code
class Button extends React.Component {
  constructor(props) {
    super(); // 😬 We forgot to pass props
    console.log(props);      // ✅ {}
    console.log(this.props); // 😬 undefined 
  }
  // ...
}

如果在从构造函数调用的某个方法中发生这种情况,则调试可能更具挑战性。 这就是为什么我建议总是传递super(props),即使它不是绝对必要的:

class Button extends React.Component {
  constructor(props) {
    super(props); // ✅ We passed props
    console.log(props);      // ✅ {}
    console.log(this.props); // ✅ {}
  }
  // ...
}

这样可以确保在构造函数退出之前设置this.props。

最后一点React用户可能会对此感到好奇。

您可能已经注意到,当您在类中使用Context API时(使用遗留的contextTypes或React 16.6中添加的现代contextType API),上下文将作为第二个参数传递给构造函数。

那么为什么我们不写super(props, context)呢?我们可以,但上下文的使用频率较低,所以这个陷阱并没有那么多。

随着类字段的提议,这整个陷阱大多数都会消失。如果没有显式构造函数,则会自动传递所有参数。这允许像state = {}这样的表达式包含对this.props或this.context的引用(如果需要)。

有了Hooks,我们甚至没有super或this。但那是另一天的话题。

这与事实并不遥远 - 事实上,这就是它的。

当React添加对类的支持时,它不仅仅增加了对ES6类的支持。目标是尽可能支持广泛的类抽象。目前尚ClojureScript,CoffeeScript,ES6,Fable,Scala.js,TypeScript或其他解决方案在定义组件方面的成功程度。所以React故意不关心是否需要调用super - 即使是ES6类。

Why Do We Write super(props)?
hooks
类字段提案
计划
作用
不清楚