Reactで 'this' is not allowed before 'super()'

背景

React.js&Next.js超入門第2版を読みながらサンプルを試していると、突然

1
2
3
4
5
6
7
8
9
10
11
12
13
14
src/Rect.js
Line 12:5: 'this' is not allowed before 'super()' no-this-before-super
Line 13:5: 'this' is not allowed before 'super()' no-this-before-super
Line 14:5: 'this' is not allowed before 'super()' no-this-before-super
Line 15:5: 'this' is not allowed before 'super()' no-this-before-super
Line 16:5: 'this' is not allowed before 'super()' no-this-before-super
Line 17:5: 'this' is not allowed before 'super()' no-this-before-super
Line 18:5: 'this' is not allowed before 'super()' no-this-before-super
Line 19:24: 'this' is not allowed before 'super()' no-this-before-super
Line 21:13: 'this' is not allowed before 'super()' no-this-before-super
Line 22:12: 'this' is not allowed before 'super()' no-this-before-super
Line 23:14: 'this' is not allowed before 'super()' no-this-before-super
Line 24:15: 'this' is not allowed before 'super()' no-this-before-super
Line 25:21: 'this' is not allowed before 'super()' no-this-before-super

とエラーが出てしまった。

エラーが起こったコード

エラーが起こったコードはこちら

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
constructor(props) {
this.x = props.x
this.y = props.y
this.width = props.w
this.height = props.h
this.color = props.c
this.radius = props.r
this.style = {
backgroundColor: this.color,
position: "absolute",
left: this.x + "px",
top: this.y + "px",
width: this.width + "px",
height: this.height + "px",
borderRadius: this.radius + "px"
}
}

原因

原因はエラーメッセージにある通り、super()を呼び出す前にthisを使ってはいけないということ。

修正後のコードはこちら

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
constructor(props) {
super(props)
this.x = props.x
this.y = props.y
this.width = props.w
this.height = props.h
this.color = props.c
this.radius = props.r
this.style = {
backgroundColor: this.color,
position: "absolute",
left: this.x + "px",
top: this.y + "px",
width: this.width + "px",
height: this.height + "px",
borderRadius: this.radius + "px"
}
}

thisを参照する前にsuperを呼べば問題ありません。

そして、Reactの話ではなく、ES6の話でした。
https://eslint.org/docs/rules/no-this-before-super

まとめ

ES6をちゃんと理解できていないので、問題の所在も怪しかった(React云々の話ではない)。ちゃんと学んでいきます。

参考図書

React.js&Next.js超入門第2版