2017-06-07 9 views
0

私はmobxと反応し始めました(それは素晴らしいチームです、btw。!)、私は私の店に少し問題があります。私は非同期的に、既存のAPIからいくつかのデータをフェッチして、私の店でいくつかの既存の観測を更新するには、このデータを使用したい:複数の機能を必要としないように、この約束を書き直すにはどうすればいいですか?

class StationStore { 

    @observable stations = [] 

    loadStations() { 
    fetch('http://localhost:3000/api/station/getStations') 
    .then(function(response) { return response.json() }) 
    .then(stations=>this.parseStations(stations)); 
    } 

    @action parseStations(stations) { 
    var newStations = stations.map((station)=>{ 
     let s = new Station; 
     s.id=station.id; 
     s.name=station.Text; 
     s.deviceType=station.DeviceType; 
     return s; 
    }); 
    this.stations.replace(newStations); 
    } 
} 

あなたが見ることができるように、私は2つの別々の機能に私のロジックを分割する必要があるために、 this.stationsにアクセスできるようになります。私は地図を入れて、loadStations()の2番目のに置き換えようとしましたが、()ですが、がそこに定義されていないので、私は私の店にアクセスできません。

どうすればこの問題を解決できますか?

+1

あなたの問題を解決する必要があります。 – Ryan

+0

'this'がそこで定義されていない場合、' loadStations() 'の2番目の' .then() 'で' this.parseStations(stations) 'をどのように呼び出すことができますか? – binki

答えて

1

使用var self = this; `this`が定義されるように、矢印の機能を使用し

class StationStore { 
    @observable stations = []; 

    loadStations() { 
     var self = this; 
     fetch('http://localhost:3000/api/station/getStations') 
      .then(function (response) { 
       return response.json() 
      }) 
      .then(stations => { 
       self.stations.replace(stations.map((station) => { 
        let s = new Station; 
        s.id = station.id; 
        s.name = station.Text; 
        s.deviceType = station.DeviceType; 
        return s; 
       })); 
      }); 
    } 
} 
+0

'self'変数を導入する必要はありません。また、あなたはアクションラッパーを失った – Alik

関連する問題