はじめに
Reactを使っていて少しハマったところがあったので、備忘録としてまとめました。
開発構成
BabelでES6,JSXをトランスパイルするという構成です。
困ったこと
stateを更新しようとしてthis.setStateを何気なく実行すると、以下のように怒られてしまいます。
Uncaught TypeError: Cannot read property 'setState' of undefined
原因
React.createClass()
では全てのメソッドが自動的にthisにbindingされるという仕様なんですが、
ES6におけるReact componentsではその自動bindingが採用されていないためでした。なので、さっきのthisはundefined
となってエラーとなってしまってました。
この詳細はReactの公式ブログに記載されています。
React v0.13.0 Beta 1 | React
React.createClass has a built-in magic feature that bound all methods to this automatically for you. This can be a little confusing for JavaScript developers that are not used to this feature in other classes, or it can be confusing when they move from React to other classes.
対処法
明示的にメソッドをbindingさせてあげればOKです。
先ほど紹介したReactの公式ブログでは、以下のようにconstructer内でそれを行ってます。
class Counter extends React.Component {
constructor() {
super();
this.tick = this.tick.bind(this);
}
tick() {
...
}
...
}
補足
React and ES6 - Part 3, Binding to methods of React class (ES7 included)
この記事では、アロー関数を用いた方法や、ES7の機能を用いた方法などbindingに関して色々紹介してくれてます。