React super(props) 是否被弃用?

Is React super(props) deprecated?

我一直使用类似于

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

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

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

我的猜测是您的编辑器向您展示了 已被 弃用的 super(props, context) 签名的描述。 link 它指向的是关于旧上下文 API 如何消失的全部内容,而那个特定的调用签名是正在离开的内容的一部分。

不过,我还没有听说过普通 super(props) 会消失,您应该可以安全地继续使用它。

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

超级(道具) :

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

超级():

  • 如果您没有在构造函数中使用 this.props 则无需传递 props 到 super().

  • 而不是this.props,你总是可以使用道具.

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

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

它看起来像一个错误。请参阅 - here 进行解释,并且有一个 link 来源。

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

npm install --dev @types/react

当你的代码在@latest

npm install --also=dev @types/react

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