什么时候通过propssuper()分很重要,为什么?

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

推荐答案

当一个人需要通过propssuper()级考试时,只有一个原因:

When you want to access 100 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', … }
    }
}

请注意,通过或不通过propssuper都有no effect关于constructor之外this.props的后续用法.也就是说,rendershouldComponentUpdate或事件处理程序always可以访问它.

这在苏菲·阿尔伯特(Sophie Alpert)的answer篇关于类似问题的文章中有明确的表述.


文件-State and Lifecycle, Adding Local State to a Class, point 2-建议:

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

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

(感谢@MattBrowne的链接)

Reactjs相关问答推荐

eslint -无法解析模块的路径@web3modal/ethers/react导入/no-unresolved

URL参数和React路由中的点

如何访问子集合中的文档?

使用Next.js和Next-intl重写区域设置

点击页脚链接时,如何更改ReactJS导航栏中的活动菜单项(样式为Tailwind CSS)?

ctx.strokeStyle 在 canvas html 5 中不起作用

Next.js 和理智 | npm run build 时预渲染页面/时发生错误

useEffect内部的RETURN语句在首次按钮点击事件中似乎无效的原因是什么?

使用jest如何覆盖对象的模拟?我正在使用`jest.mock()`来模拟对象,并希望 for each 测试用例覆盖模拟.

无法使axiosmockadapter正常工作

在 Nextjs13 应用程序目录中呈现从 supabase 获取的数据

改变输入的默认值时出现问题:number react-hook-form

当每个元素都可拖动时,移动设备上的滚动列表出现问题

AWS 全栈应用程序部署教程构建失败

意外的标记.您可能需要一个合适的加载器来处理这种文件类型.书?.img? /*#__PURE__*/React.createElement("img",

如何从一组对象映射 MUI 5 图标并更改其 colored颜色 ?

如何用实际的br标签替换axios响应中的br标签?

哪个 PrivateRouter 实现更好:高阶组件还是替换?

如何在 React x 中返回组件?

React Router 6,一次处理多个搜索参数