LoginSignup
5
6

More than 5 years have passed since last update.

react内で、ajax通信の結果を、setStateしたい時のthisのbindの仕方

Last updated at Posted at 2017-06-29

ブログに記事を写しました。react-nativeで、ajax通信の結果を、setStateしたい時のthisのbindの仕方

reactと組み合わせてjqueryを使っている時に、ajaxでPOST通信を送ろうとした。この時のmthisのbindの位置が直感とはずれてたので、メモ。

thisにjqueryの関数自身が入る

ex1.js
export default class Example extends React.Component

  constructor() {
    this.example = this.example.bind(this);
  }

  example() {
    $.ajax({
      type: 'POST',
      url,
      data: JSON.stringify(data),
      success(res) {
        // ここのthisの話
        this.setState({ res });
      },
      error(error) {
        // ここのthisの話
        this.setState({ error });
      },
    });
  }
}

そりゃそうか。直さなきゃ。

thisにjqueryの関数自身が入る〜Part2〜

ajaxメソッドを読んだ時に、thisをbindしなきゃいけないから、きっと関数の閉じカッコの後ろにつけてあげればいいんだろうな。。。から。

ex1.js
export default class Example extends React.Component

  constructor() {
    this.example = this.example.bind(this);
  }

  example() {
    $.ajax({
      type: 'POST',
      url,
      data: JSON.stringify(data),
      success(res) {
        // ここのthisの話
        this.setState({ res });
      },
      error(error) {
        // ここのthisの話
        this.setState({ error });
      },
    }).bind(this);
  }
}

しかしこれもajax関数自身がthisに入ってくる。

そんで以下を試したら解決

解決策

結局綺麗に(?)bindするのが無理だったので、変数に格納して取って置くことにした。すっきりしないけど、困ったら愚直に

ex1.js
export default class Example extends React.Component

  constructor() {
    this.example = this.example.bind(this);
  }

  example() {
    const _this = this;
    $.ajax({
      type: 'POST',
      url,
      data: JSON.stringify(data),
      success(res) {
        // ここのthisの話
        this.setState({ res });
      }.bind(this),
      error(error) {
        // ここのthisの話
        this.setState({ error });
      },
    }).bind(this);
  }
}

あれ、no_underscore_dungleのlinter errorでてる。。。(気にしない)

5
6
9

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6