Open ide opened 8 years ago
It should work with ...args
also.
React is lenient, so constructor() { super(); } works, so this is just a stylistic preference. š 3
I would argue this is more than a stylistic preferenceāit can actually lead to bugs. Consider this example, where a method that relies on props is invoked from the constructor:
class Foo extends Component {
constructor()
super();
this.state = this.getInitialState();
}
getInitialState() {
// ERROR: `props` is `undefined` because the super constructor did not receive `props`
const x = this.props.y + 1;
return { x }
}
}
@OliverJAsh in your example, super()
will set this.props
for you - React.Component
does not use any of the constructor arguments, to handle this case.
@ljharb
If you want to use this.props in the constructor, you need to pass props to super. Otherwise, it doesn't matter because React sets .props on the instance from the outside immediately after calling the constructor.
In my example, I'm calling a method (which relies on this.props
) from the constructor. So, it will be undefined
.
interesting, fair enough.
In that case, the rule should probably enforce props, context
or ...args
I would also like to see this rule in place, i.e. if props
is used in the constructor then constructor(props)
and super(props)
must exist. An example of where this might cause problems:
class Foo extends Component {
constructor() {
super();
this.someObj = {
bar: this.props.intl.formatMessage(...),
};
}
}
Eslint will not currently thrown any errors here. I would suggest enforcing no use of this.props
in the constructor and instead recommend just using props
.
This rule would check for:
React is lenient, so
constructor() { super(); }
works, so this is just a stylistic preference.