栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用es6类时,React中的“ super()”和“ super(props)”有什么区别?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用es6类时,React中的“ super()”和“ super(props)”有什么区别?

只有一种原因需要传递

props
super()

当您要

this.props
在构造函数中访问时。

通过:

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
,以
super
没有影响
对以后的用途
this.props
之外
constructor
。也就是说
render
shouldComponentUpdate
或事件处理程序
始终 可以访问它。

这是索菲·阿尔珀特(Sophie Alpert)对类似问题的回答中明确指出的。


建议使用“ 状态和生命周期,将本地状态添加到类,第2点”中的文档:

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

props

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

(感谢@MattBrowne的链接)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/616450.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号