react-nativeで、ajax通信の結果を、setStateしたい時のthisのbindの仕方
reactと組み合わせてjqueryを使っている時に、ajaxでPOST通信を送ろうとした。この時のmthisのbindの位置が直感とはずれてたので、メモ。
thisにjqueryの関数自身が入る
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しなきゃいけないから、きっと関数の閉じカッコの後ろにつけてあげればいいんだろうな。。。から。
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するのが無理だったので、変数に格納して取って置くことにした。すっきりしないけど、困ったら愚直に
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でてる。。。(気にしない)