问题描述
我一直都用类似的东西
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
var1 : undefined,var2 : 'etc...',}
}
}
但是今天我注意到,在使用VS Code工作时,super(props)
上有一条删除线,以前从未有过!!
有什么变化? (在弹出窗口中指向文档的链接不是很有帮助)
解决方法
我的猜测是,您的编辑器正在向您显示不推荐使用 的超级(属性,上下文)签名的描述。它指向的链接是关于旧的上下文API的消失方式,而特定的调用签名是剩下的一部分。
但是,我还没有听说过简单的super(props)
消失的消息,您应该可以继续使用它了。
它看起来像个错误。请参阅-here以获取解释,并且有指向源的链接。
,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
,仅使用super()代替super(props)
超级(道具):
- 使用此功能,我们可以在构造函数中访问和使用 this.props 对象。
super():
-
如果您在构造函数中未使用 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...',}; } }