REACT.js 变量在 api 请求中未被接受

REACT.js variables not accepted in api request

我正在尝试通过在我的请求中添加变量和 console.log 来提高我的代码的效率和可重用性。但由于某种原因它不起作用,我不知道为什么!完整代码可在以下位置找到:https://codesandbox.io/s/wispy-lake-6h051

这个有效:

  state = {
    lastWeek: '2020-11-09',
    today: '2020-11-12',
    selectedBase: 'USD',
    firstDateValues: null,
    fifthDateValues: null
  };

  getAPI = async() => {
    const START_DATE = this.state.lastWeek;
    const END_DATE = this.state.today;
    const BASE = this.state.selectedBase;
    
    const response = await fixer.get(`?start_at=${START_DATE}&end_at=${END_DATE}&base=${BASE}`, {
    });
    console.log(BASE) ---> output: USD
    console.log(response.data.rates[START_DATE].USD) --> correct data
}

但事实并非如此:

  state = {
    lastWeek: '2020-11-09',
    today: '2020-11-12',
    selectedBase: 'USD',
    firstDateValues: null,
    fifthDateValues: null
  };

  getAPI = async() => {
    const START_DATE = this.state.lastWeek;
    const END_DATE = this.state.today;
    const BASE = this.state.selectedBase;
    
    const response = await fixer.get(`?start_at=${START_DATE}&end_at=${END_DATE}&base=${BASE}`, {
    });
    console.log(BASE) ---> output: USD
    console.log(response.data.rates[START_DATE].BASE) --> output: undefined 
}

为什么?

你需要做的就是改变

response.data.rates[START_DATE].BASE

esponse.data.rates[START_DATE][BASE]

因为如果您使用的是 .BASE,这意味着 BASE 密钥,而不是来自 BASE 变量的密钥