前端/移动开发面试题更新 2026-08-05

在 React 类组件中,调用 super() 与调用 super(props) 有何区别?请说明两者在初始化 props 时的不同作用。

前端/移动开发技术原理React

考察说明

考查对 React 类组件中 super 调用方式的理解,特别是 props 在构造函数中的可用性。

回答思路

  1. 【回答框架 1】super() 是调用父类(React.Component)的构造函数,而 super(props) 则会携带 props 参数调用父类构造函数。区别在于:在子类构造函数中,只有调用了 super(props) 后,this.props 才会被正确初始化,从而可以直接在构造函数内访问 this.props。
  2. 【回答框架 2】如果只调用 super(),React 仍会在组件的其他生命周期方法(如 render、componentDidMount)中自动设置 this.props,但在构造函数内部访问 this.props 会得到 undefined。因此,若需要在构造函数中使用 props,就必须传入 super(props)。
  3. 【回答框架 3】更详细的机制是:super() 调用了 React.Component 的基础构造函数,而通过 super(props) 将 props 赋值给了 this.props。在 React 的经典实现中,当实例化类组件时,构造函数中的 this.props 是由父类构造函数设置的,所以不传 props 会导致 this.props 未定义。
  4. 【关键点 1】super() 不传 props,构造函数内 this.props 为 undefined;
  5. 【关键点 2】super(props) 传递 props,构造函数内即可访问 this.props;
  6. 【关键点 3】React 会在生命周期中自动设置 this.props,但构造函数需显式传入。
  7. 【易错点 1】误认为 super() 与 super(props) 在所有场景下等价,忽视构造函数内 this.props 的差异;
  8. 【易错点 2】在构造函数中未调用 super() 或未正确传参会引发错误,例如 this 未初始化。