javascript - 在 JavaScript 中使用解构的正确方法

标签 javascript reactjs setstate

我从数据库中获取数据,其中我只需要两个数组。使用两个变量,我得到了我需要的结果,但我明白,这段代码没有正确编写。甚至 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 
   });

最佳答案

map方法使用调用数组中每个元素上提供的函数的返回值创建一个新数组。
请注意上面一行中的“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);
});

关于javascript - 在 JavaScript 中使用解构的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57878577/

相关文章:

javascript - 类型错误 : Cannot read property 'FieldValue' of undefined

javascript - 为什么状态没有按预期更新?

javascript - Appium 和 UiAutomator2 自动化已经打开的应用程序

javascript - JavaScript 数组的动态条件

javascript - 可变路由器参数a路由

reactjs - 我如何在 React 中使用 Materialise css 中的 DropDown

flutter - Getx Bottomsheet setstate 不更新

javascript - setState() 函数不起作用,我无法更新我的状态。我怎么解决这个问题?

javascript - 根据后面出现的所需项目数组对对象数组进行排序

php - 如何从 PHP 中的 JSON.stringify 中删除反斜杠?