Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixins and duplicate methods in React.js

Getting more and more into the awesomeness that is React.js and I've started to use Mixins more.

One thing I noticed, is that both my mixin and my component can have a componentDidMount method — And both functions will be called, so defining it in the component won't override the one in the mixin and vice versa.

Here's an example:

var MyMixin = {
    componentDidMount: function() {
        // Do something when component is mounted
        console.log("Mixin fn ran");
    }   
};

var Component = React.createClass({
    mixins: [MyMixin],
    componentDidMount: function() {
        // Do something when component is mounted
        console.log("Component fn ran");
    }
});

Now, the question is wether this is by design or just a coincidence that this works. The lifecycle methods are very useful (To bind and unbind events for instance), so it's not uncommon that both my component and mixins will want to rely on those. The documentation doesn't say anything about this, and I'm wanting to know if I'm setting myself up for a bad time down the road by doing this.

Another question is do I have some kind of control over which method is called first? The one in the mixin or the one in the component.

like image 680
Ahrengot Avatar asked Oct 09 '14 12:10

Ahrengot


1 Answers

Yes, it's intentional, and the main factor that makes mixins very powerful in React.

So what happens is:

  • for the 'component...' functions, they're called in the order of mixin[0], mixins[1], ..., component
  • propTypes, and the return value of getInitialState and getDefaultProps are merged
  • other conflicting method names, or conflicts while merging the above results in an error
like image 104
Brigand Avatar answered Oct 15 '22 14:10

Brigand