【问题标题】:REST calls from a react component来自反应组件的 REST 调用
【发布时间】:2019-02-01 14:09:59
【问题描述】:

我正在尝试使用不同的 JSON 复制相同的代码 here,但未加载数据。

请帮忙,我不确定代码中缺少什么。

import React from 'react';

export default class ItemLister extends React.Component {
    constructor() {
        super();
        this.state = { items: [] };
    }

    componentDidMount() {
  fetch('http://media.astropublications.com.my/api/drebar_landing.json')
      .then(result=>result.json())
      .then(items=>this.setState({items}));
    }

    render() {
      return(
        <ul>
            {this.state.items.length ?
              this.state.items.map(item=><li key={item.id}>{item.Title}</li>) 
              : <li>Loading...</li>
            }
        </ul>
     )
    }
  }

【问题讨论】:

  • 你能不能通过console.log(items)来检查你是否得到了json。

标签: json reactjs


【解决方案1】:

您的 api 响应包含一个对象 ArticleObject 并且 ArticleObject 具有对象数组,因此您需要将 items.ArticleObject 设置为状态。

查看以下解决方案以更好地理解

componentDidMount() {
  fetch('http://media.astropublications.com.my/api/drebar_landing.json')
      .then(result=>result.json())
      .then(items=>this.setState({items:items.ArticleObject}));
    }

【讨论】:

    猜你喜欢
    • 2016-09-25
    • 2018-09-19
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    相关资源
    最近更新 更多