【问题标题】:Understanding why super() is deprecated in a React class component理解为什么在 React 类组件中不推荐使用 super()
【发布时间】:2020-12-30 13:28:34
【问题描述】:

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

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)

【问题讨论】:

标签: reactjs typescript deprecated


【解决方案1】:

只有在构造函数中使用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); //{}
  }
  // ...
}

【讨论】:

    【解决方案2】:

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

    npm install @types/react
    

    【讨论】:

    • 帮我解决了,而其他答案没有
    • 它有效,我建议也添加--save-dev,所以它会转到devDependencies
    【解决方案3】:

    看起来可选的上下文参数已被弃用,因为它引用了遗留的 React 上下文(pre v16.3)。你使用的是什么版本的 React?

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

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

    【讨论】:

    • 我正在使用 React 16.13.1。让我感到困惑的是,我什至没有使用那个可选参数。
    • constructor(props, context) 的继承者是什么?
    • 看起来我可以只调用 super() 而不是 super(props)。我从这里得到了这个想法:stackoverflow.com/questions/30571875/…
    • 这应该没问题,除非你需要在构造函数中使用this.props。后继者在组件外部定义。 reactjs.org/docs/context.html
    • @Steven React' docs 推荐使用 super(props) 所以我认为你可以保持原样。弃用消息实际上是一个错误,有人已经提交了patch 来修复它。
    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-23
      • 2017-11-04
      • 2011-10-22
      • 2011-04-11
      相关资源
      最近更新 更多