【问题标题】:How to access keys inside api objects如何访问 api 对象中的键
【发布时间】:2020-03-24 06:50:51
【问题描述】:

我正在尝试从 API 的选择选项中获取国家/地区 https://covid19.mathdro.id/api/countries.

github 链接:https://github.com/nitink66/corona-updates

它过去两天都可以正常工作,但现在我只是在选择选项中获取数字而不是国家/地区。 我应该如何访问这些国家,以便我可以在选择选项标签上显示它。

  const respCountries = await Axios.get("https://covid19.mathdro.id/api/countries");
  const countries = Object.keys(respCountries.data.countries);
  this.setState({
    confirmed: respApi.data.confirmed.value,
    recovered: respApi.data.recovered.value,
    deaths: respApi.data.deaths.value,
    countries
  });
}

renderCountryOptions(){
  return this.state.countries.map((country,i)=>{
      return <option key={i}>{country}</option>
  });
}



【问题讨论】:

    标签: reactjs rest api


    【解决方案1】:

    删除Object.keys,这是不必要的,并且您的国家/地区更新状态不正确

    const countries = respCountries.data.countries;
    
    this.setState({
        confirmed: respApi.data.confirmed.value,
        recovered: respApi.data.recovered.value,
        deaths: respApi.data.deaths.value,
        countries: countries,
      });
    
    renderCountryOptions(){
      return this.state.countries.map((country,i)=>{
          return <option key={i}>{country.name}</option>
      });
    }
    

    【讨论】:

    • 抛出错误 TypeError: Cannot read property 'map' of undefined
    • 我发现你的国家/地区的 setState 不正确,我更新了答案,你可以再试一次@Nitin
    【解决方案2】:

    {country.name} 国家现在是具有其他属性的对象。

    【讨论】:

      猜你喜欢
      • 2012-01-09
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 2020-02-03
      • 2018-07-15
      • 2017-10-29
      • 1970-01-01
      相关资源
      最近更新 更多