1. ホーム
  2. javascript

[解決済み] Javascriptのlet変数の再代入と構造化 [重複] [重複

2022-10-19 04:21:27

質問

私のReactアプリではairbnbのeslintスタイルガイドを使用していますが、destructuingを使用しないとエラーが発生します。

以下のような状況で、私はまず let を使って2つの変数を割り当てます。 latitudelongitude を、位置情報オブジェクトの配列の最初の項目の座標に変換します。そして、ユーザーが自分の位置へのアクセスを私に与えた場合、それらの値を再割り当てするために、私は破壊を使用しようとします。

let latitude = locations[0].coordinates[1];
let longitude = locations[0].coordinates[0];

if (props.userLocation.coords) {
  // doesn't work - unexpected token
  { latitude, longitude } = props.userLocation.coords;

  // causes linting errors
  // latitude = props.userLocation.coords.latitude;
  // longitude = props.userLocation.coords.longitude;
}

の中の構造化 if 文の内部では unexpected token エラーが発生します。

昔ながらの方法で変数を再割り当てすると ESlint: Use object destructuring エラーが発生します。

どのように解決するのですか?

 ({ latitude, longitude } = props.userLocation.coords);

構造化解除は let , const または var 宣言であるか、ブロックステートメントと区別するために式コンテキストの中にある必要があります。