2017-06-13 5 views
2

jsonをフェッチするときに異なる応答が表示されるのはなぜですか?私は矢印機能を使用すると動作し、そうでない場合は動作しません。矢印出力の有無にかかわらず、矢印出力機能を持つ別の出力をフェッチする

constructor(props){ 
    super(props); 
    this.state = { 
    data: [], 
    }; 
    this.url = 'https://fcctop100.herokuapp.com/api/fccusers/top/recent'; 
} 

矢印機能を取得:

fetch(url) 
    .then((response) => { 
    return response.json() 
    }).then((json) => { 
    this.setState({data: json}); 
    console.log('parsed json', json) 
    }).catch((ex) => { 
    console.log('parsing failed', ex) 
    }); 

コンソール上で戻り値:

parsed json Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, 90 more… ] 

をそして、私は矢印の機能を使用しないときに出力が異なります。

fetch(url) 
    .then((response) => { 
    return response.json() 
    }).then(function(json) { 
    this.setState({data: json}); 
    console.log('parsed json', json) 
    }).catch((ex) => { 
    console.log('parsing failed', ex) 
    }); 

返品:

parsing failed TypeError: this is undefined Stack trace: 
listCampers/<@http://localhost:3000/static/js/bundle.js:18177:17 

答えて

2

arrow functionthis自身を持ち、親範囲(それは成分を反応させる。この場合に)を意味しません。あなたはあなたが所有することで、この場合にはthisはグローバルスコープを参照するので、あなたは、thisを設定する必要がfunction使用している場合(ブラウザでそれwindowである)、またはあなたが使用している場合strict modethisになりますundefined

.then(function(json) { 
    this.setState({data: json}); 
    console.log('parsed json', json) 
}.bind(this)) 
^^^^^^^^^^^ 
1

はいなぜなら後者の場合に

fetch(url) 
    .then((response) => { 
    return response.json() 
    }).then(function(json) { 
    this.setState({data: json}); ///The error is given here 
    console.log('parsed json', json) 
    }).catch((ex) => { 
    console.log('parsing failed', ex) 
    }); 

あなたはthis.setStateを使用しているが、成功コールバックは、コンポーネントを反応させるのコンテキストにバインドされていないので、this.then関数自体のコンテキストを参照しますので、setState

ながら最初のケースでは、this矢印内側利用できません関数は、あなたのケースでは、反応コンポーネントのコンテキスト であり、setStateが利用可能なので、適切な出力を得る親コンテキストを参照します。

関連する問題