【发布时间】: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