2017-12-07 9 views
0

私はそれをコンソールに応答を記録しますが、次にすべてのコードを下に置く状態に設定することはできません。Google Distance Matrix Api React Js Cantは州に距離を設定します

getDist(dest){ 
var self = this; 
var origin = this.state.location, 
    destination = this.state.dest, 
    service = new window.google.maps.DistanceMatrixService(); 

    service.getDistanceMatrix(
    { 
     origins: [origin], 
     destinations: [destination], 
     travelMode: window.google.maps.TravelMode.DRIVING, 
     avoidHighways: false, 
     avoidTolls: false, 
     unitSystem: window.google.maps.UnitSystem.IMPERIAL 
     }, 
     this.callback 
    ); 
} 

callback(response, status) { 
    const self = this; 
    if(status === "OK") { 
     console.log(response); 
     var dest = response.destinationAddresses[0]; 
     var dist = response.rows[0].elements[0].distance.text; 
     return response; 
    } else { 
     alert("Error: " + status); 
    } 
    } 

IVEは、コールバック関数の状態を設定しようとしましたが、それはsetState({})は関数ではありませんと言っています。 iveはこれを行うことによって状態を設定しようとしましたthis.setState({ distFromLoc: self.callback })しかし、コールバック関数コードを自分の知識の終わりに達している状態ではない状態に設定し、私が扱う他のWeb開発者は私たちのロジック。

私は、約36のジョブのリストを繰り返しているので、2秒間状態を設定できるだけで、検索のたびに、そのジョブが検索している人に十分近いかどうかをチェックします。

編集1 -Andy事前に

ありがとう:私はあなたが多分間違って何イム私を示すことができるだろうこれ以上のエラーdoes notのそれはまだ文句を言わない私はデータを返してみましょう私のコードを編集していますか?

それを呼び出すクラスを追加しようとしています。なぜなら、関数をpromise関数に変換する関数を使用することはできません。

updateSearchResults(data) { 
this.setState({ 
    searching: true, 
}); 
var self = this; 
var output = []; 
console.log('Here we will search the db using user data for suitable jobs'); 
console.log('do some math to work out how many pagination we need for the amount of returned jobs and update the state accordingly'); 
data.forEach(item => { 
    console.log('before'); 
    this.getDist(item.postcode).then(function (res){ 
    console.log('after'); 
    console.log(this.state.distFromLoc); 
    if (this.state.location === '') { 
     if (item.option === 'Part Time' && this.state.partTime && !this.state.weekend){ 
     if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null) { 
      console.log('1'); 
      output.push(item) 
     } else if (this.state.keywords === ''){ 
      console.log('2'); 
      output.push(item); 
     } 
     } else if (item.option === 'Weekends' && this.state.weekend && !this.state.partTime){ 
     if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null) { 
      console.log('3'); 
      output.push(item) 
     } else if (this.state.keywords === ''){ 
      console.log('4'); 
      output.push(item); 
     } 
     } else if (item.option === 'both' && this.state.weekend && this.state.partTime){ 
     if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null) { 
      console.log('5'); 
      output.push(item) 
     } else if (this.state.keywords === ''){ 
      console.log('6'); 
      output.push(item); 
     } 
     } else if (!this.state.weekend && !this.state.partTime) { 
     if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null) { 
      console.log('7'); 
      output.push(item) 
     } else if (this.state.keywords === ''){ 
      console.log('8'); 
      output.push(item); 
     } 
     } 
    } else if (this.state.distFromLoc <= this.state.distance) { 
     console.log(this.state.distFromLoc); 
     console.log(this.state.distance); 
     if (item.option === 'Part Time' && this.state.partTime && !this.state.weekend){ 
     if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null) { 
      console.log('9'); 
      output.push(item) 
     } else if (this.state.keywords === ''){ 
      console.log('10'); 
      output.push(item); 
     } 
     } else if (item.option === 'Weekends' && this.state.weekend && !this.state.partTime){ 
     if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null) { 
      console.log('11'); 
      output.push(item) 
     } else if (this.state.keywords === ''){ 
      console.log('12'); 
      output.push(item); 
     } 
     } else if (item.option === 'both' && this.state.weekend && this.state.partTime){ 
     if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null) { 
      console.log('13'); 
      output.push(item) 
     } else if (this.state.keywords === ''){ 
      console.log('14'); 
      output.push(item); 
     } 
     } else if (!this.state.weekend && !this.state.partTime) { 
     if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null) { 
      console.log('15'); 
      output.push(item) 
     } else if (this.state.keywords === ''){ 
      console.log('16'); 
      output.push(item); 
     } 
     } 
    } 
    }) 
    .catch(function (err){ 
    console.log(err); 
    }); 
}); 
window.setTimeout(function() { 
self.setState({ 
    dataToShow: output, 
    searching: false, 
    current: 1, 
}); 
const dataLength = self.state.dataToShow.length 
self.setState({ 
    amountOfJobs: dataLength 
})}, 10000) 
} 

getDist(dest){ 
var self = this; 
const wrappedCallback = (...args) => this.callback(...args); 
var origin = this.state.location, 
    destination = dest, 
    service = new window.google.maps.DistanceMatrixService(); 

    service.getDistanceMatrix(
    { 
     origins: [origin], 
     destinations: [destination], 
     travelMode: window.google.maps.TravelMode.DRIVING, 
     avoidHighways: false, 
     avoidTolls: false, 
     unitSystem: window.google.maps.UnitSystem.IMPERIAL 
     }, wrappedCallback 
    ); 
} 

callback(response, status) { 
    const self = this; 
    if(status === "OK") { 
     console.log(response); 
     var dest = response.destinationAddresses[0]; 
     if (response.rows[0].elements[0].status === "ZERO_RESULTS"){ 

     } else if (response.rows[0].elements[0].status === "OK"){ 
      var dist = response.rows[0].elements[0].distance.text; 
      this.setState({ 
      distFromLoc: dist 
      }) 
     } 
    } else { 
     alert("Error: " + status); 
    } 
    } 

私は何か間違っていることを知っています。私はちょうどそれが正確に何かを取り除きます。

現在のエラーは次のとおりです。TypeError:未定義のプロパティ 'then'を読み取ることができませんなぜ関数に約束していますか?

答えて

0

これはバインディングの問題であり、JavaScriptのクラスを使用しないようにする主な理由の1つです。あなたの問題があるのはここです:

service.getDistanceMatrix({ 
    origins: [origin], 
    destinations: [destination], 
    travelMode: window.google.maps.TravelMode.DRIVING, 
    avoidHighways: false, 
    avoidTolls: false, 
    unitSystem: window.google.maps.UnitSystem.IMPERIAL 
    }, 
    this.callback 
); 

あなたはthis.callbackとしてコールバックを提供する場合、あなたは機能に渡しています。しかし、その関数が呼び出されると、呼び出しコードがGoogleのAPIに入っているため、実際には何かを知る必要があるコンテキストがなくなります。thisこの問題には3つの解決策があります。それはthis

//boundCallback will now always have the correct value for "this" 
const boundCallback = this.callback.bind(this); 

2であるかを知っているように、

1)のみ)

//fat arrow always takes the value of "this" from surrounding scope 
const wrappedCallback = (...args) => this.callback(...args); 

3)はあなたのコンポーネントのReact.createClass()を使用してください(脂肪矢印機能でES6を包み)関数をバインド これは私の推奨する解決策です。class Comp extends React.Componentを使用する代わりにReact.createClass()でコンポーネントを作成すると、すべての機能が自動的にバインドされるため、混乱する必要はありません。this.callbackは常に正しいです。

+0

2番目の番号で)私はこれを変更する必要があります。コールバック 'を' const boundCallback = this.callback.bind(this); '私は正しい?私はそれを開始した場所にwrappedCallbackを返します。 –

+0

私は自分のコードを –

+0

に変更して私の質問を更新しました。あなたは私にReact.createClass()のための手伝いをさせることができますか?私はReact.createClass()を使用する方法を知らないそれ。 –

0

あり、代替解決策になるが、それはグローバル変数を使用していますがあります

window.callback = function() {}; 

window.callback = (code, name) => { 
    me.setState({stateVariable: code});  
}; 

あなたはそれに応じて、このコードを変更し、それが矢印でグローバルに宣言されましたので、あなたのコードの任意の場所(でコールバックを使用する場合があります文脈を保つ機能、それは閉鎖です)

関連する問題