【问题标题】:Is React super(props) deprecated?不推荐使用 React super(props) 吗?
【发布时间】:2021-01-03 22:41:21
【问题描述】:

我一直用类似的东西

class MyComponent extends React.Component {
    constructor(props) {
        super(props)
        
        this.state = {
            var1 : undefined,
            var2 : 'etc...',
        }
    }
}

但今天我注意到在 VS Code 中工作时,super(props) 上有一条删除线,这是以前从未有过的!?

发生了什么变化? (弹出窗口中的文档链接不是很有帮助)

【问题讨论】:

标签: reactjs visual-studio-code react-class-based-component


【解决方案1】:

super(props) 未被弃用。见官方文档-https://reactjs.org/docs/react-component.html#constructor

这实际上不是错误。这是与代码编辑器、Typescript 和 React 相关的错误。你可以在这里阅读 - https://github.com/microsoft/TypeScript/issues/40511

好消息是解决了。您可以在这里找到解决方案 - https://github.com/DefinitelyTyped/DefinitelyTyped/pull/47784

【讨论】:

    【解决方案2】:

    似乎是一个错误。 如果您更新您的“@types/react”,它将解决问题。

    npm install --dev @types/react
    

    当你的代码在@latest上时

    npm install --also=dev @types/react
    

    【讨论】:

      【解决方案3】:

      它看起来像一个错误。请参阅 - here 以获得解释,并且有一个来源的链接。

      【讨论】:

        【解决方案4】:

        只使用 super() 而不是 super(props)

        超级(道具)

        • 通过使用this,我们可以在构造函数中访问和使用this.props对象。

        超级()

        • 如果您没有在构造函数中使用 this.props,则无需将 props 传递给超级()。

        • 您始终可以使用 props,而不是 this.props

        • 不将 props 传递给 super 也没关系,不管是否将其传递给 super,this.props在渲染函数中仍然可用。

          class MyComponent extends React.Component {
              constructor(props) {
                  super();
          
                  this.state = {
                       var1 : undefined,
                       var2 : 'etc...',
                  };
              }
          }
          

        【讨论】:

        • 这只会为那些打开类型检查的人创建一个错误,因为目前 React 类型中的构造函数没有零参数重载。
        【解决方案5】:

        我的猜测是,您的编辑器正在向您显示 已弃用的 super(props, context) 签名的描述。它指向的链接是关于旧的上下文 API 是如何消失的,而特定的调用签名是即将消失的一部分。

        但是,我还没有听说过一个普通的super(props) 会消失,你应该可以安全地继续使用它。

        【讨论】:

        • 我什至不知道有一个 super(props,context) 签名,因此我从未使用过它。但是 VS Code(或他们使用的任何 linter)只会导致一个普通的 super(props) 被标记。我现在可能会忽略它,直到有人在他们身边修复它。
        猜你喜欢
        • 2020-12-30
        • 2011-01-25
        • 1970-01-01
        • 2022-01-03
        • 2017-05-23
        • 2018-05-06
        • 2019-12-09
        相关资源
        最近更新 更多