LoginSignup

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

setIntervalで使用する関数のthisについて

教えてほしい

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"));

0

2Answer

thisの扱いは無名関数かどうかでなくアロー関数かどうかで変わります。

1

Comments

  1. @udagawah1015

    Questioner
    アロー関数はスコープを確立しないのですね。ありがとうございました。

多分thisをbindする必要があるような気がする。

後class componentは一世代前のやり方なので、function componentの書き方を覚えたほうが良いかも。

1

Comments

  1. @udagawah1015

    Questioner
    アドバイスありがとうございます。ご指摘どおり関数の方でやってみようと思います。

Your answer might help someone💌