I find that using the componentWillMount lifecycle method to set the initial state ...
componentWillMount() { this.state = { comments: [] }; }
... a little easier than using a constructor. Namely, because when using the constructor, you must call super() .
constructor() { super(); this.state = { comments: [] }; }
Not only that, but if your component is passed props and / or state , you also need to manually pass them.
constructor(props, state) { super(props, state); ... }
I had no problems using componentWillMount , but I almost never saw anyone use it to set the state (unless they avoid es6 and have classes). I get that we have access to the constructor in the es6 class, but why use it when you need to make a manual transition to the parent constructor, and there is a ready-made and expecting an excellent life cycle, so you do not need to do this
Just curious if there was a real practical reason or if it is basically just a preference.
javascript reactjs
Chev
source share