TypeError:无法读取未定义的属性“未定义”

时间:2020-08-10 05:45:57

标签: javascript arrays reactjs state typeerror

我有这个数组:

        super(props);
        this.state = {
            data: [{
                baseCurrency: 'GBP',
                baseAmount: 0,
                convertToCurrency: 'USD',
                rates: [],
                currencies: []
            },
                ]
        }

当我尝试在render()函数中访问它时,出现错误

const {currency,rates,baseCurrency,baseAmount,convertToCurrency} = this.state.data;

const result = Number.parseFloat(baseAmount * rates [convertToCurrency])。toFixed(2);

如果我不使用数组声明this.state,则不会发生此问题。

2 个答案:

答案 0 :(得分:1)

您只能传播特定的对象,因为this.state.data是一个数组:

const [
  { currencies, rates, baseCurrency, baseAmount, convertToCurrency },
] = this.state.data;

更具可读性:

const [firstItem] = this.sate.data;
const {
  currencies,
  rates,
  baseCurrency,
  baseAmount,
  convertToCurrency,
} = firstItem;

答案 1 :(得分:1)

像这样解构数据

let res = {
  data: [{
    baseCurrency: 'GBP',
    baseAmount: 0,
    convertToCurrency: 'USD',
    rates: [],
    currencies: []
  }, ]
}

const {
  data: [{
    baseCurrency,
    baseAmount,
    convertToCurrency
  }]
} = res;

console.log(baseCurrency, baseAmount, convertToCurrency);