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

Ste*_*ven 77 deprecated typescript reactjs

我是 React 的新手,我正在使用最新版本的 React 学习 React 组件生命周期。我对下面部分代码的“超级”调用标有已弃用的警告。我很难理解这个,因为那里的很多文档仍然使用“超级”,而且我不确定继任者是什么,即使从反馈中链接的完整文章也是如此。有任何想法吗?谢谢。

class App extends Component {
  constructor(props) {
    super(props);
  }
}
Run Code Online (Sandbox Code Playgroud)

这是警告:

class App extends Component {
  constructor(props) {
    super(props);
  }
}
Run Code Online (Sandbox Code Playgroud)

Kir*_*rev 39

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
  }
  // ...
}
Run Code Online (Sandbox Code Playgroud)

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

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


wee*_*eix 27

super(props);尚未弃用。弃用消息实际上是由React 的类型定义文件中的错误引起的,并且已经在@types/react 16.9.51 中修复。只需升级软件包即可:

npm install @types/react
Run Code Online (Sandbox Code Playgroud)

  • 为我解决了这个问题,而其他人的答案却没有 (3认同)

Dmi*_* S. 14

似乎不推荐使用可选的上下文参数,因为它指的是旧版 React 上下文(v16.3 之前)。你使用的是什么版本的 React?

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

我没有将 React 与 TypeScript 一起使用。也许 React 映射已经过时了。

  • @Steven [React' docs](https://reactjs.org/docs/state-and-lifecycle.html#adding-local-state-to-a-class) 建议使用 `super(props)` 所以我认为你可以保持原样。弃用消息实际上是一个错误,有人已经提交了一个[补丁](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/47784)来修复它。 (7认同)
  • 看起来我可以只调用 super() 而不是 super(props) 。我从这里得到了这个想法:/sf/ask/2140031281/ Between-super-and-superprops-in-react-when-using-e (3认同)

小智 13

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