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;
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?
javascript ecmascript-6 reactjs ecmascript-next
Brandon Jun 05 '16 at 19:28 2016-06-05 19:28
source share