【问题标题】:Fetch API Data in React在 React 中获取 API 数据
【发布时间】:2018-12-14 14:38:14
【问题描述】:

我正在调用 fetchData(url) 来检索 json 数据。我的 API 数据格式是这样的: 页号:1 页面大小:100 页数:5 总记录数:600 项目: 0:{ 编号:1, 主题:ACC } 1:{…}

我的反应 ItemList.js:

import React, {Component} from 'react';
class ItemList extends Component{
constructor(){
    super();
    this.state={
        Items:[],
        hasErrored: false,
        isLoading: false
    };
}
 //retrieve data using fetch
 fetchData(url){
    this.setState({isLoading: true});
    fetch(url)
    .then((response)=>{
        if (!response.ok){
            throw Error(response.statusText);
        }
        this.setState({isLoading:false});
        return response;
    })


    .then((response)=>{response.Items.json()})
    .then((Items)=>{
         this.setState({Items});

    })
    .catch(()=>this.setState({hasErrored:true}));
}
componentDidMount(){
    this.fetchData(myURL)
}

render(){
    if (this.state.hasErrored){
        return <p>There was an error loading the items</p>;
    }
    if (this.state.isLoading){
        return <p>Loading...</p>;
    }

    return(
        <div>  
        <ul>

            {this.state.Items.map((item)=>(
                <li key={item.ID}>{item.SUBJECT}</li>
            ))}
        </ul>
        </div>
    );
  }
  }
export default ItemList;

它总是返回“加载项目时出错”。 Items 数组始终为空。但是,如果我将 api url 复制并粘贴到浏览器,它就可以正常工作。不确定我的代码有什么问题?谢谢。

【问题讨论】:

  • 您的呼叫进入catch 块。从那里开始。在catch(()=&gt; 中添加错误参数,如catch((error)=&gt; 并检查。此外,您可以使用检查元素并在Network 选项卡中查看您的请求。

标签: reactjs


【解决方案1】:

response.Items.json()

这行会抛出一个错误,因为当你访问响应时它在转换为 JSON 格式之前只是一个字符串

使用

response.json()

然后,我将更改一点@Kabbany 的答案,因为 response.statusText 总是返回与错误代码相关的一般错误消息。然而,大多数 API 通常会在正文中返回某种有用、更人性化的消息。

关键是,不是抛出错误,而是抛出响应,然后在 catch 块中处理它以提取正文中的消息:

fetch(url)
      .then( response => {
        if (!response.ok) { throw response } // Return the complete error response for debugging purposes
        return response.json()  //we only get here if there is no error
      })
      .then( json => {
        this.setState({Items: json.Items }); 
      })
      .catch( error => {
        () => this.setState({ hasErrored: true, error }) // Save both error flag and error detail so you can send it to tools like bugsnag
      })

【讨论】:

    【解决方案2】:

    我认为应该是这样的:

    fetch(url)
    .then((response)=>{
        if (!response.ok){
            throw Error(response.statusText);
        }
        this.setState({isLoading:false});
        return response.json();
    })
    .then((resp)=>{
         this.setState({Items: resp.Items});
    })
    .catch(()=>this.setState({hasErrored:true}));
    

    【讨论】:

    • 谢谢,但我尝试了 Items: resp.Items 但它不起作用。
    • 无论如何你错过了response.json()的很大一部分,如果它不存在,则响应将无法以json格式提供
    猜你喜欢
    • 2021-12-23
    • 2021-12-16
    • 2021-09-27
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    相关资源
    最近更新 更多