2

言語: Reactjs とバニラ JavaScript

質問は単なる一般的な JavaScript コールバックの質問ですが、React コードを追加して、この苦境に陥った方法を示します。

タランティーノ風に、私の紛らわしい失敗を見てみましょう。

成功コールバックのパラメータとしてコールバックを送信しようとしています

navigator.geolocation.getCurrentPosition(success(dataLoaded), error, options); 

しかし、 docsによると、「pos」は成功コールバックの「唯一の入力パラメーター」であると想定されているため、気に入らなかった.

巻き戻して、何が私をこの混乱に陥らせたのかを考えてみましょう。

コールバックを使用して、React アプリに非同期フェッチが完了したことを確認し、それ自体をレンダリングします。

onDataLoaded: function() {
    this.setState({
        postsLoaded: true,
    });
  },
  componentDidMount: function(){
    WebAPIUtils.fetchComponentData(this.onDataLoaded);
  },
render: function() {
    if(!this.state.postsLoaded){
        return (<div className="Loading">Loading...</div>);
    }
    return (
      <div>
        //Components can be rendered now since their data is loaded. 
      </div>
    );
  }

以下のコードが成功したら、そのコールバックを実行する必要があります。

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function success(pos) {
  var crd = pos.coords;

  console.log('Your current position is:');
  console.log('Latitude : ' + crd.latitude);
  console.log('Longitude: ' + crd.longitude);
  console.log('More or less ' + crd.accuracy + ' meters.');
  //Here I want to execute my callback to render.
};

function error(err) {
  console.warn('ERROR(' + err.code + '): ' + err.message);
};

navigator.geolocation.getCurrentPosition(success, error, options);

しかし、 geolocation.getCurrentPosition にはコールバックが規定されているため、そのコールバックを成功コールバックのパラメーターとして渡す方法はないようです。

そのコールバックを成功コールバックの追加パラメータとして渡す方法はありますか? コールバックのパラメーターとしてコールバックが送信されるのは奇妙に思えますが、ロケーション モジュールの外部でロケーション ロジックも処理するように元のコールバックを作成するのも面倒です。

4

1 に答える 1

3

バインドを使用してください!

navigator.geolocation.getCurrentPosition(
  success.bind(null, dataLoaded), 
  error, 
  options);

//

function success(dataLoaded, pos) {
  var crd = pos.coords;

  console.log('Your current position is:');
  console.log('Latitude : ' + crd.latitude);
  console.log('Longitude: ' + crd.longitude);
  console.log('More or less ' + crd.accuracy + ' meters.');
  dataLoaded();
}

thisこれにより、基本的に、引数を置き換えて事前入力できる関数の新しいバージョンが作成されます。したがって、渡されるコールバックは、呼び出されたときにgetCurrentPosition関数になる単一パラメーター関数です。possuccess

于 2015-09-29T20:07:02.070 に答える