了解为什么在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> (+1 overload)
@deprecated
@see - https://reactjs.org/docs/legacy-context.html
'(props: any,context?: any): Component<any,any>' is deprecated ts(6385)

解决方法

仅当您要在构造函数中使用super(props);时,才需要this.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); //{}
  }
  // ...
}
,

我认为这是jslint中的错误。该代码显然没有使用context参数。

,

super(props);尚未被弃用。弃用消息实际上是由a bug in React's type definition file引起的,并且已在 @ types / react 16.9.51 中修复。只需升级软件包,您就可以开始了:

npm install @types/react
,

似乎已弃用了可选的context参数,因为它引用了旧版React上下文(v16.3之前的版本)。您使用的是哪个版本的React?

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

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