I'm new at React/React Native and I just began working on a company and, thus, working on existing projects. The thing is, I can't understand this Creation Lifecycle Hooks on the begining of this code:
export default class ListResult extends React.Component {
constructor(props) {
super(props);
this.state.answers = props.navigation.state.params.answers;
this.state.saving = props.navigation.state.params.saving;
this.state.loading = false;
}
state = {
answers: null,
saving: false,
loading: true,
location: null,
dialogLocation: false,
latitude: '',
longitude: '',
};
location = null;
latitude = '';
longitude = '';
}
Can someone please provide me some explanation why is he using the constructor to initialize the state, and after that, used state to define variables, and then, after that, he also set some values to those variables?
Its a common mistake and even emphasised in related docs:
This code roughly should fixed to:
As for explanation, he uses both class instances and a constructor (why?), in "modern" React, with class components you shouldn't use the constructor (instead, use class properties).
When a class is defined, the class instances evaluated first and then the constructor called, thats why he overrides the initial values in their instances.