【问题标题】:Fetch some data from an api with React使用 React 从 api 获取一些数据
【发布时间】:2019-09-16 06:55:17
【问题描述】:

我正在尝试从 api 获取一些数据,但由于某种原因它无法正常工作,我也尝试使用 Object.key

我已经做了几次 api fetch 但我想我不明白这种 JSON 格式

这是我的代码:

class CryptoNews extends Component {
    constructor(props){
        super(props);
        this.state = {
            news: []
        }
    }

    componentDidMount(){
fetch('https://min-api.cryptocompare.com/data/v2/news/?feeds=cryptocompare,cointelegraph,coindesk&extraParams=YourSite')
.then(res => res.json())
.then(data => this.setState({
    news: data
})
)}

  render() {
    return (
      <div>
        {this.state.news.map((key) => (
            <div key={key.id}>
            <h2>{key.body}</h2>
        </div>
        ))}
      </div>
    )
  }
}

【问题讨论】:

    标签: arrays reactjs components fetch


    【解决方案1】:

    您需要从响应对象中获取Data 属性。 所以:

    news: data.Data
    

    【讨论】:

      【解决方案2】:

      您正在尝试获取 Data 数组并将其设置为 this.state.news。

      JSON 消息的格式是这样的。

      {
       "Type":100,
       "Message":"News list successfully returned",
       "Promoted":[],
       "Data":[],
       "RateLimit":{},
       "HasWarning":false
      }
      

      您的 componentDidMount 方法应如下所示

      componentDidMount(){
       fetch('https://min-api.cryptocompare.com/data/v2/news/? 
       feeds=cryptocompare,cointelegraph,coindesk&extraParams=YourSite')
       .then(res => res.json())
       .then(data => this.setState({
          news: data.Data
       })
      )}
      

      【讨论】:

        猜你喜欢
        • 2021-09-26
        • 1970-01-01
        • 2018-01-31
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-27
        相关资源
        最近更新 更多