Mixins and repeating methods in React.js

More and more in awesomeness, this is React.js, and I started using Mixins more.

One thing that I noticed is that my myminin and my component can have a componentDidMount method. And both functions will be called, so the definition of this component will not be redefined in the mixture and vice versa.

Here is 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, is it by design or just a coincidence that this works. Lifecycle methods are very useful (for example, to bind and untie events), so it’s not uncommon that both my component and mixins will want to rely on them. The documentation says nothing about this, and I want to know if I am not set up for a bad time by doing this.

Another question: do I have any control over which method is called first? One in a mixture or one in a component.

+6
source share
1 answer

Yes, this is intentional, and the main factor that makes mixins very powerful in Reactivity.

So what happens:

  • for functions "component ...", they are called in the order mixin [0], mixins [1], ..., component
  • propTypes, and the return value of getInitialState and getDefaultProps are combined
  • other conflicting method names or conflicts when combining the above results with an error
+14
source

Source: https://habr.com/ru/post/976491/


All Articles