“super()”之间的区别是什么?和“超(道具)” in React当使用es6类时? [英] What's the difference between "super()" and "super(props)" in React when using es6 classes?

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

问题描述

如果通过 props super()是重要的,为什么?

  class MyComponent extends React.Component {
constructor(props){
super(); //还是超级(道具)?
}
}


解决方案

只有一个原因,当需要通过道具 super()



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



Passing:

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

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

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

console.log(this.props)
// - >未定义

// Props参数仍然可用
console.log(props)
// - > {icon:'home',...}
}

render(){
//外部构造函数
console.log(this.props)
// - > {icon:'home',...}
}
}

请注意通过或不通过道具 super 对<$ c以后使用不起作用 $ c> this.props 外面构造函数。这是 render shouldComponentUpdate 或事件处理程序始终可以访问它。 p>

这是在一个Ben Alpert的 answer 给类似的问题。






文档 - 状态和生命周期,将本地状态添加到类中,第2点 - 推荐:


类组件应始终使用 props 调用基础构造函数。


但是,没有提供任何理由。我们可以推测它是由于子类化或将来的兼容性。



(感谢@MattBrowne的链接)


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

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

解决方案

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

When you want to access this.props in constructor.

Passing:

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

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

Not passing:

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', … }
    }
}

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.

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


The documentation—State and Lifecycle, Adding Local State to a Class, point 2—recommends:

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.

(Thanks @MattBrowne for the link)

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

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