Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

reactjs - Understanding why super() is deprecated in a React class component

I'm new to React and I'm learning about the React component lifecycle with the latest version of React. My "super" call of the partial code below is flagged with the deprecated warning shown. I've had trouble understanding this one, as a lot of documentation out there still uses "super", and I'm not sure what the successor is, even from the full article linked in the feedback. Any ideas? Thanks.

class App extends Component {
  constructor(props) {
    super(props);
  }
}

Here is the warning:

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need super(props); only if you gonna use this.props in the constructor. Otherwise you can use super(); If you use super(); in the constructor it is not a problem that outside of the constructor you will call this.props. You can read about it in the following link: 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
  }
  // ...
}

It can be even more challenging if this happens in some method that's called from the constructor. And that's why I recommend always passing down super(props), even through it isn't necessary.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...