2016-04-23 7 views
2

javascriptを使用してフェッチコール内でコンストラクタ変数を取得して反応できません。 .then(function(json)コールバック内のthis.state.numXLabelsの値が欲しいですが、TypeError:未定義(...)のプロパティ 'state'を読み込めません。これを行う正しい方法は?関連するコード:プロビジョニングでコンストラクタ変数を取得

はTypeError:未定義のプロパティを読み取ることができません「状態」(...)

import React, { Component } from 'react' 
class StockGraph extends Component { 

constructor(props) { 
    super(props); 
    this.state = { numXLabels: 0 } 
    var url = 'https://www.quandl.com/api/v3/datasets/WIKI/MSFT'+ 
      '.json?api_key=bCRpjzvgPNkxLzqAv2yY'; 
    fetch(url) 
    .then(function(response) { 
     return response.json() 
    }) 
    .then(function(json) { 
     console.log(this.state.numXLabels); 
     //this.setState({ 
     // numXLabels: 30 
     //}) 
    }) 
    } 
... 
+0

見[コンストラクタ関数は約束を返すように悪い習慣ですか?]持っている(http://stackoverflow.com/q/24398699/1048572)一般的な問題のため、反応はおそらくありますが、特有の解決策です。 – Bergi

答えて

3

は、状態を使用するか、あなたのコンポーネントに反応のコンストラクタでAJAX呼び出しを行うためにしようとしないでくださいその代わり、ということを置きます。 の中のcomponentWillMountのようにすぐに呼び出されます。また、あなたのajaxコールバック内のthis.stateにアクセスするには、thisをこの関数にバインドする必要があります。を使用するが最も簡単な方法です。

class StockGraph extends Component { 
    constructor(props) { 
     super(props); 
     this.state = { numXLabels: 0 } 
    } 

    componentWillMount() { 
     var url = 'https://www.quandl.com/api/v3/datasets/WIKI/MSFT'+ 
      '.json?api_key=bCRpjzvgPNkxLzqAv2yY'; 
     fetch(url) 
     .then((response) => { 
      return response.json() 
     }) 
     .then((json) => { 
      console.log(this.state.numXLabels); 
      //this.setState({ 
      // numXLabels: 30 
      //}) 
     }) 
    } 
    ... 
+0

ありがとう!拘束力が鍵となりました。 componentWillMountに移動することは、構造的な清潔さにもいいです。太い矢印の構文は素晴らしいヒントです。 .then(function(json){ console.log(this.state.numXLabels); } .bind(this))のようにすることもできます。 – joshlevy89

関連する問題