“super()"和“super()"有什么区别?和“超级(道具)"使用 es6 类时在 React 中? [英] What's the difference between "super()" and "super(props)" in React when using es6 classes?

查看:19
本文介绍了“super()"和“super()"有什么区别?和“超级(道具)"使用 es6 类时在 React 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

何时将 props 传递给 super() 很重要,为什么?

When is it important to pass props to super(), and why?

class MyComponent extends React.Component {
  constructor(props) {
    super(); // or super(props) ?
  }
}

推荐答案

需要将 props 传递给 super() 的原因只有一个:

There is only one reason when one needs to pass props to super():

当你想在构造函数中访问 this.props 时.

When you want to access this.props in constructor.

通过:

class MyComponent extends React.Component {    
    constructor(props) {
        super(props)

        console.log(this.props)
        // -> { icon: 'home', … }
    }
}

没有通过:

class MyComponent extends React.Component {    
    constructor(props) {
        super()

        console.log(this.props)
        // -> undefined

        // Props parameter is still available
        console.log(props)
        // -> { icon: 'home', … }
    }

    render() {
        // No difference outside constructor
        console.log(this.props)
        // -> { icon: 'home', … }
    }
}

请注意,将 props 传递或不传递给 superthis.props 的后续使用没有影响构造函数之外.即 rendershouldComponentUpdate 或事件处理程序总是可以访问它.

Note that passing or not passing props to super has no effect on later uses of this.props outside constructor. That is render, shouldComponentUpdate, or event handlers always have access to it.

这在 Sophie Alpert 的一个 回答类似的问题.

This is explicitly said in one Sophie Alpert's answer to a similar question.

文档—状态和生命周期,将本地状态添加到类,第 2 点—建议:

类组件应始终使用 props 调用基本构造函数.

Class components should always call the base constructor with props.

但是,没有提供任何理由.我们可以推测它要么是因为子类化,要么是为了未来的兼容性.

However, no reason is provided. We can speculate it is either because of subclassing or for future compatibility.

(感谢@MattBrowne 提供链接)

(Thanks @MattBrowne for the link)

这篇关于“super()"和“super()"有什么区别?和“超级(道具)"使用 es6 类时在 React 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆