理解为什么在 React 类组件中不推荐 super()

我是 React 的新手,我正在学习 React 组件的生命周期和最新版本的 React。下面部分代码的“超级”调用被标记为不推荐的警告。我很难理解这个问题,因为很多文档仍然使用“ super”,而且我不确定后继者是什么,甚至从反馈中链接的完整文章中也看不出来。有什么想法吗?谢谢。

class App extends Component {
constructor(props) {
super(props);
}
}

以下是警告:

constructor React.Component<any, any, any>(props: any, context?: any): React:Component<any, any, any> (+1 overload)
@deprecated
@see - https://reactjs.org/docs/legacy-context.html
'(props: any, context?: any): Component<any, any, any>' is deprecated ts(6385)
25022 次浏览

可选的上下文参数似乎不被推荐,因为它引用了遗留的 React 上下文(pre v16.3)。你用的是什么版本的 React?

Https://reactjs.org/docs/legacy-context.html

我还没有使用过 React with TypeScript。也许 React 映射已经过时了。

我认为这是 jslint 中的一个 bug,代码显然没有使用上下文参数。

只有在构造函数中使用 this.props时才需要 super(props);,否则可以使用 super(); 如果在构造函数中使用 super();,那么在构造函数之外调用 this.props就不是问题。 你可浏览以下连结: Https://overreacted.io/why-do-we-write-super-props/

class Button extends React.Component {
constructor(props) {
super(); //we forgot to pass props
console.log(props); //{}
console.log(this.props); //undefined
}
// ...
}

如果这种情况发生在从构造函数调用的某个方法中,则会更具挑战性。这就是为什么我建议总是传递 super(props),即使它不是必要的。

class Button extends React.Component {
constructor(props) {
super(props); //we passed props
console.log(props); //{}
console.log(this.props); //{}
}
// ...
}

super(props);还没有被废弃。实际上是由 React 类型定义文件中的 bug引起的弃用消息,并且在 @ type/response 16.9.51时已经修复。只要升级软件包,你就可以开始了:

npm install @types/react