thisの扱いは無名関数かどうかでなくアロー関数かどうかで変わります。
Like!
codepenでReactを使用しています。
setIntervalの第一引数に関数だけを渡すと、thisのメソッド参照でエラーが発生します。
無名関数でその関数を渡すと問題なく実行されます。
関数だけの場合と、無名関数で渡した場合のthisは違うのでしょうか?
this.setState is not a function
this.timerID = setInterval(this.tick, 1000);
例)
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
componentDidMount() {
// this.timerID = setInterval(() => this.tick(), 1000);
this.timerID = setInterval(this.tick, 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({ date: new Date() });
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(<Clock />, document.getElementById("root"));
thisの扱いは無名関数かどうかでなくアロー関数かどうかで変わります。
@udagawah1015
Questioner多分thisをbindする必要があるような気がする。
後class componentは一世代前のやり方なので、function componentの書き方を覚えたほうが良いかも。
@udagawah1015
Questioner