Javascript重新分配带有分解功能的let变量 [英] Javascript re-assign let variable with destructuring

查看:89
本文介绍了Javascript重新分配带有分解功能的let变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的React应用程序中,我使用的是airbnb的eslint样式指南,如果不使用解构方法,它将引发错误.

In my React app I am using airbnb's eslint style guide which will throw an error if I do not use destructuing.

在以下情况下,我首先使用let将两个变量latitudelongitude分配给位置对象数组中第一项的坐标.然后,如果用户允许我访问其位置,则尝试使用解构来重新分配其值.

In the situation below, I first use let to assign the two variables latitude and longitude to the coordinates of the first item in an array of location objects. Then I try to use destructuring to re-assign their values if the user has given me access to their location.

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错误.

Destructuring inside the if statement causes an unexpected token error.

以旧方式重新分配变量会导致ESlint: Use object destructuring错误.

Re-assigning the variables the old fashioned way causes an ESlint: Use object destructuring error.

推荐答案

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

解构需要在letconstvar声明之后进行,或者必须在表达式上下文中进行区分以将其与block语句区分开.

Destructuring needs to be either after a let, const or var declaration or it needs to be in an expression context to distinguish it from a block statement.

这篇关于Javascript重新分配带有分解功能的let变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆