ES6 React: Will ES.Next @autobind bind methods only once for each instance?

there are questions / articles on numerous ways to handle bindings in ES6 React, but most of them don't seem to address the issue described in React docs ( emphasis ):

We recommend binding event handlers in the constructor so that they are bound only once for each instance :

constructor(props) { super(props); this.state = {count: props.initialCount}; this.tick = this.tick.bind(this); } 

In context, they advise against built-in method bindings, such as:

 //using .bind() <div onClick={this.tick.bind(this)}> // ES6 anon arrow functions <div onClick={() => this.tick()}> // ES.Next :: operator <div onClick={::this.tick}> 

Sure. But the recommended binding solution for each method in the constructor is cumbersome with many methods, so I looked at ES.Next @autobind decorator at the class level as a simple solution:

 import { autobind } from 'core-decorators'; @autobind class Person { getPerson() { return this; } getPersonAgain() { return this; } } let person = new Person(); let { getPerson, getPersonAgain } = person; getPerson() === person; // true getPersonAgain() === person; // true 

What I cannot understand: will this decorator have the same flaw in string binding methods? those. Will the methods only bind once for each instance?

If not, is there a concise solution to avoid this error?

+2
javascript ecmascript-6 reactjs ecmascript-next
Jun 05 '16 at 19:28
source share
2 answers

Fields of the class instance and the initializers associated with them solve the problem of assigning properties with the same name as the methods inside the constructor, but with a more concise syntax. The following example is possible with the Babel properties of the class properties :

 class Counter extends React.Component { constructor(props) { super(props); this.state = {count: props.initialCount}; } tick = () => { this.setState({count: this.state.count + 1}); }; ... } 

This creates a new related tick property for each instance of Counter . This creates the same number of related functions as React.createClass .

Without an instance field and an initializer, the effect is the same (the bound tick property is created for each Counter instance), but with a more detailed syntax:

 constructor(props) { super(props); this.state = {count: props.initialCount}; this.tick = this.tick.bind(this); } tick() { this.setState({count: this.state.count + 1}); } 
+1
Sep 27 '16 at 19:18
source share

I wrote a small component that binds all the methods of other components. you can try if you want: http://www.marouen-mhiri.com/react/autobinding-es6-classes-in-react-another-approach/

0
Jun 10 '16 at 18:47
source share



All Articles