【问题标题】:How to pass and keep global variable remain unchanged in function in React?如何在 React 中传递和保持全局变量在函数中保持不变?
【发布时间】:2020-09-16 14:06:16
【问题描述】:

我是 React 新手。我正在尝试从常量文件中导入变量并在函数中使用它。这是我的演示代码。但是,如果我多次调用该函数,otherCountryList 中的国家/地区只会继续附加到COUNTRY_LIST。我怎样才能防止这种情况发生,并且每次我调用该函数时,它都会在 COUNTRY_LIST 上附加为新列表?

常量.js:

export const COUNTRY_LIST = ['USA', 'UK', 'SPAIN'];

index.js

import {COUNTRY_LIST} from './constants/constant';  
inputCountry(){
  let countryList = COUNTRY_LIST;
  //let say pushing other country to the countryList 
  for (var c = 0; c < this.otherCountryList.length; c ++){
    countryList.push(c);
  }
  console.log(countryList) //expected output:['USA', 'UK', 'SPAIN', 'AUS', 'JAPAN']
  // real output after called this function twice:['USA', 'UK', 'SPAIN', 'AUS', 'JAPAN', 'AUS', 'JAPAN']
}

【问题讨论】:

    标签: javascript reactjs list function variables


    【解决方案1】:

    使用这个:

    const countryList = [...COUNTRY_LIST];
    

    就是这样,没有 push 或 for 循环或其他任何东西。它只是复制数组。

    【讨论】:

    • 感谢您的回答,但我收到一条错误消息“constants_constant__WEBPACK_IMPORTED_MODULE_12_.COUNTRY_LIST 不可迭代”。另外,如果我使用 const 声明 countryList,我如何在 for-loop 中向它推送值?
    • WRT 问题,const 确实 not 意味着您不能修改数组(一个常见的误解),只是您不能重新分配值。你可以推送它,但你不能做像COUNTRY_LIST=[]这样的事情。
    • 这个错误,可能是你的浏览器不支持spread算子?您可以尝试 COUNTRY_LIST.slice() 代替。 console.log COUNTRY_LIST 来检查它是否正确导入,尽管从你原来的错误来看,你会认为它是正确的。
    • 谢谢!我尝试使用 const 不起作用,但 var 工作正常并解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    相关资源
    最近更新 更多