You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

CATS API技术问题:获取品种名称时控制台返回Undefined

解决CATS API获取品种名称返回Undefined的问题

嘿,我来帮你理清楚问题出在哪,以及怎么修复:

问题根源

调用https://api.thecatapi.com/v1/breeds接口返回的直接是一个猫咪品种对象的数组,不是包含breeds字段的嵌套对象,也不是单个对象。所以你现在的代码有两个核心问题:

  1. response.data.breeds是不存在的——接口返回的data本身就是品种数组,没有外层的breeds属性;
  2. response.data.name返回undefined,是因为response.data是数组,数组本身没有name属性,只有数组里的每个品种对象才带有name字段。

修改后的代码示例

axios.get('https://api.thecatapi.com/v1/breeds', options)
 .then((response) => {
    // 直接把返回的品种数组赋值给state的cats
    self.setState({ cats: response.data });
    
    // 打印所有品种名称:遍历数组逐个获取每个对象的name
    response.data.forEach(breed => {
      console.log(breed.name);
    });
    
    // 如果你只想打印第一个品种的名称,可以这么写(可选):
    // console.log(response.data[0]?.name);
 }, (error) => {
    console.log(error);
 });

渲染下拉列表的小提示

当你要在组件里生成下拉列表时,可以用state里的cats数组遍历生成选项:

<select>
  {this.state.cats.map(breed => (
    <option key={breed.id} value={breed.id}>
      {breed.name}
    </option>
  ))}
</select>

内容的提问来源于stack exchange,提问作者Dhr-RT

火山引擎 最新活动