【问题标题】:Correct way to use destructuring in JavaScript在 JavaScript 中使用解构的正确方法
【发布时间】:2019-09-10 21:42:59
【问题描述】:

我从只需要两个数组的数据库中获取数据。使用两个变量,我得到了我需要的结果,但我明白,这段代码没有正确编写。连npm都写箭头函数应该返回一些东西,所以我加了“return false”;

let flagUrls = [];
let countryNames = [];

country.map((country, index) => {
   flagUrls[index] = country.flagUrls;
   countryNames[index] = country.countryNames;
   return false;
});

this.setState({ flagUrls, countryNames });

我试过这样:

let flagsAndCountrys =  country.map((country, index) =>[country.flagUrls, country.countryNames])


this.setState({ 
   flagsAndCountrys.flagUrls,
   flagsAndCountrys.countryNames 
   });

【问题讨论】:

  • 这不是destructuring assigment 的真正问题,更多的是正确使用Array.prototype.map 的问题。 Array.prototype.map 需要一个 return 语句来创建一个新的转换结果数组。鉴于您正在尝试创建两 (2) 个数组,map() 可能不是正确使用的数组方法。您可能只使用 forEach() 甚至 for 循环。
  • 也许您可以提供country 的数据外观以及您期望flagUrlscountryNames 处理后的外观。
  • 你为什么要分开我看到它,你必须保持两个数组同步,或者你是否对这两个列表做任何事情会导致它们不同步?就像改变一个数组,而不是另一个。如果没有,那就适得其反;您将数据结构更改为另一种更难以推理的数据结构。
  • 正如@Thomas 建议的那样:您可能有一个XY problem,因为通常将相应的数据耦合到对象中是一件好事。

标签: javascript reactjs setstate


【解决方案1】:

mapmethod 在调用数组中的每个元素上使用所提供函数的 return 值创建一个新数组。
请注意上面一行中的 return 一词。你需要返回一些将被插入到新数组中的东西。

因此,使用map,您可以创建一个新数组,其中包含只有flagUrlscountryNames 字段的对象,如下所示:

let result = country.map((country, index) => {
   return {
     flagUrl: country.flagUrls,
     countryName: country.countryNames
   }
});

如果你想维护两个 flagUrls 和 countryNames 数组,你不应该使用 map。最好在这里使用 forEach,如下所示:

let flagUrls = [];
let countryNames = [];
country.forEach((country, index) => {
   flagUrls.push(country.flagUrls);
   countryNames.push(country.countryNames);
});

为此使用解构,将传递给提供的函数country 的第一个参数替换为如下值:{flagUrls, countryNames}

country.forEach(({flagUrls, countryNames}, index) => {
   flagUrls.push(flagUrls);
   countryNames.push(countryNames);
});

【讨论】:

    【解决方案2】:

    创建两个数组的正确方法是调用map 两次:

    const flagUrls = countries.map(country => country.flagUrl);
    const countryNames = countries.map(country => country.countryName);
    

    如果您只想通过一次迭代来执行此操作,那么您将不得不使用具有副作用的循环 - 类似于您所做的 map 调用,但您更愿意使用 forEach

    let flagUrls = [];
    let countryNames = [];
    countries.forEach((country, index) => {
        flagUrls[index] = country.flagUrl;
        countryNames[index] = country.countryName;
    });
    

    或者只是

    let flagUrls = [];
    let countryNames = [];
    for (const country of countries) {
        flagUrls.push(country.flagUrl);
        countryNames.push(country.countryName);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-25
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-04
      • 1970-01-01
      相关资源
      最近更新 更多