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

后端 未结 4 761
闹比i
闹比i 2020-12-05 22:33

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

相关标签:
4条回答
  • 2020-12-05 23:00

    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); //{}
      }
      // ...
    }
    
    0 讨论(0)
  • 2020-12-05 23:16

    super(props); isn't deprecated yet. The deprecation message actually caused from a bug in React's type definition file and is already fixed as of @types/react 16.9.51. Just upgrade the package and you're good to go:

    npm install @types/react
    
    0 讨论(0)
  • 2020-12-05 23:18

    It looks like the optional context parameter is deprecated because it refers to the legacy React context (pre v16.3). What version of React are you using?

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

    I have not used React with TypeScript. Maybe React mappings are out of date.

    0 讨论(0)
  • 2020-12-05 23:18

    I think this is a bug in jslint. The code obviously isn't using the context parameter.

    0 讨论(0)
提交回复
热议问题