【问题标题】:React-native using a state variable while getting data from fetch从 fetch 获取数据时使用状态变量进行 React-native
【发布时间】:2021-02-28 22:56:19
【问题描述】:

我正在尝试创建一个简单的 Expo Snack,它可以在用户选择的两种货币之间进行转换。

当有人从下拉列表中选择一个选项时,我有两个状态变量会更新,我想使用这些状态变量的值从获取中获取数据。

<Picker
  selectedValue={this.state.curr1}
  style={{ height: 25, width: 125 }}
  onValueChange={(itemValue, itemIndex) => this.setState({ curr1: itemValue })}>
  <Picker.Item label="US Dollar" value="USD" />
  <Picker.Item label="Euro" value="EUR" />
</Picker>

所以我在这里将 state 变量的值设置为 USD 或 EUR。

convert() {
    fetch('https://open.exchangerate-api.com/v6/latest')
      .then((response) => response.json())
      .then((json) => {
        const currency1 = this.state.curr1;
        const currency2 = this.state.curr2;
        alert(currency1);
        alert(currency2);
        const currRate1 = json.rates.currency1;
        const currRate2 = json.rates.currency2;
        alert(currRate1);
        alert(currRate2);

这就是我卡住的地方。第一个警报 (Currency1&2) 显示值为 USD 和 EUR。 但是,当尝试使用它们来调用下半年的费率时,我对两者都“未定义”。

如果我这样做

json.rates.EUR; 
json.rates.USD;

它正确调用费率。无法准确确定如何格式化,因此我可以使用选择器中的状态变量来调用费率。

【问题讨论】:

    标签: javascript reactjs expo


    【解决方案1】:

    因为 currency1 和 currency2 的值​​是字符串,所以您会得到未定义。要将这些值用作属性,您应该添加括号:

    json.rates.[currency1]
    json.rates.[currency2]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 2020-06-03
      • 1970-01-01
      • 2019-07-16
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      相关资源
      最近更新 更多