未能做出反应的承诺

问题描述 投票:1回答:1

我刚刚开始学习反应,我正在尝试做的是设置一个调用特定API的简单组件,传递一个参数。

Axios:https://github.com/axios/axios API:https://dog.ceo/dog-api/

我的代码

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

class Itemlist extends React.Component {
    constructor() {
        super();
        this.state = {items: [], breedName: ''}
        this.fetchSubBreeds = this.fetchSubBreeds.bind(this);
        this.updateInputValue = this.updateInputValue.bind(this);
    }

    fetchSubBreeds() {
        axios.get('https://dog.ceo/api/breed/' + this.state.breedName + '/list')
        .then((response) => {
            this.setState({items: response.data.message})
        })
        .catch((error) => {
            this.setState({items: []});
            console.log(error);
        });
    }

    updateInputValue(evt) {
        this.setState({breedName: evt.target.value});
    }

    render() {
        return(
            <div>
                <label for='breed'>Breed name: </label>
                <input type='text' name='breed' 
                    onBlur={() => this.fetchSubBreeds()} 
                    onChange={(evt) => this.updateInputValue(evt)}>
                </input>
                <ul>
                    {this.state.items.map(item => <li key={item.id}>{item}</li>)}
                </ul>  
            </div>
        );
    }
}

export default Itemlist

当一个品种存在时,我得到了正确的子品种列表,但是当params错误时,似乎catch函数会休眠,因为我收到此错误:

TypeError: this.state.items.map is not a function
render

  34 |             onChange={(evt) => this.updateInputValue(evt)}>
  35 |         </input>
  36 |         <ul>
> 37 |             {this.state.items.map(item => <li key={item.id}>{item}  </li>)}
  38 |         </ul>  
  39 |     </div>
  40 | );

错误的API响应:https://dog.ceo/api/breed/random/list

处理响应错误的正确方法是什么?

json reactjs promise axios
1个回答
3
投票

问题是,无论您是否提供有效品种,API仍会以状态代码200(这意味着在HTTP土地上取得成功)作出响应。由于API服务器使用成功代码进行响应,因此永远不会调用catch语句。因此,您需要在then语句而不是catch中进行检查。解析响应并检查status属性是否等于“error”。

fetchSubBreeds() {
    axios.get('https://dog.ceo/api/breed/' + this.state.breedName + '/list')
    .then((response) => {
        if(response.data.status==="error"){
           return console.log("breed doesn't exists"); //or whatever logic
        } else {
            this.setState({items: response.data.message})
        }

    })
    .catch((error) => {
        this.setState({items: []});
        console.log(error);
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.