Table of contents
Open Table of contents
React 类组件的 constructor 一定要调用 super(props) 吗?
- 在 ES6 类继承中(React 类组件本质上是这样),只有调用了 super() 之后才能安全使用 this,包括 this.state 的初始化、方法绑定等。如果你在 constructor 中需要用 this(比如初始化 state 或绑定方法),就必须在任何 this 操作之前调用 super()。
- 虽然 super(props) 不是直接“初始化组件状态”,但它确保了父类的构造函数执行,让 this 的引用成立。否则会直接导致运行时错误。
- 总结:在 constructor 里如果使用 this,必须先调用 super(),React 组件推荐 super(props)。
super 方法里必须传 props 吗?
- 传递 props 给 super(props) 的常规做法,是因为父类 React.Component 会用它来初始化 this.props,这样你就可以在 constructor 内访问 this.props。
- 不过,即使不传 props 给 super(只写 super()),React 也会在构造函数之后,把 props 再次赋值到实例。这是为了兼容各种旧的/其它语言的类组件方案。
- 但!如果你在 constructor 内部需要访问 this.props,而你没有传 props 给 super,this.props 会是 undefined,直到 constructor 执行完 React 再赋值,此时就容易引发 bug,也不易排查。
- 所以最佳实践是:始终写 super(props),确保 this.props 在整个构造函数期间都可用,代码一目了然没有隐患。
还有什么注意事项?
- 如果你的类组件还用到了 React Context 的 context 参数(如旧的 contextTypes 或新的 contextType),context 作为第二个参数传递,也可以 super(props, context),但这种情况相对较少。
- 在使用 class fields(类字段,state = {} 这种写法)或 Hooks(函数组件)时,这些“super(props)”的难题基本消失,因为你无需手动写 constructor。