如何在React组件中显示API数据?

时间:2019-05-19 17:58:40

标签: javascript json reactjs api

这是我的json URL:

http://ec2-13-233-199-251.ap-south-1.compute.amazonaws.com/api/keyword/modi

{
    "Republic": [
        {
            "headline": "Now, Robert Vadra scoffs at PM Modi's Kedarnath visit, exclaims 'Wow !! What’s going on ...'",
            "link": "https://www.republicworld.com/india-news/general-news/now-robert-vadra-scoffs-at-pm-modis-kedarnath-visit-exclaims-wow-whats-going-on-dot",
            "date": "2019-05-19 20:51:07.261913",
            "category": null,
            "sentiment": null
        }
    ],
    "Ndtv": [
        {
            "headline": "Blog: Is Modi Moving Mamata Banerjee's Cheese In Bengal?",
            "link": "https://www.ndtv.com/blog/is-modi-moving-mamata-banerjees-cheese-in-bengal-2039156?pfrom=home-opinion",
            "date": "2019-05-19 20:51:50.218228",
            "category": null,
            "sentiment": null
        }
    ],
    "Indiatv": [
        {
            "headline": "Modi's Kedarnath Yatra is being widely covered by media, this is gross violation of MCC: TMC to Election Commission",
            "link": "https://www.indiatvnews.com/news/india-election-2019-modi-kedarnath-yatra-is-being-widely-covered-by-media-this-is-gross-violation-of-mcc-tmc-to-election-commission-520982",
            "date": "2019-05-19 20:50:48.145723",
            "category": null,
            "sentiment": null
        }
    ],
    "Thehindu": [
        {
            "headline": "Early life stress can modify DNA expression, a study finds",
            "link": "https://www.thehindu.com/sci-tech/science/early-life-stress-can-modify-dna-expression-a-study-finds/article27172334.ece",
            "date": "2019-05-19 20:50:51.485027",
            "category": null,
            "sentiment": null
        }
    ],
    "Zeenews": [
        {
            "headline": "Lok Sabha election 2019: PM Modi offers prayers at Badrinath temple\n",
            "link": "https://zeenews.india.com/video/india/lok-sabha-election-2019-pm-modi-offers-prayers-at-badrinath-temple-2204365.html",
            "date": "2019-05-19 20:50:55.60367",
            "category": null,
            "sentiment": null
        }
    ],
}

我编写了以下代码,以在我的react组件中显示新闻来源Republic,Ndtv和Zeenews的标题链接日期:

class keywordNews extends Component {
    state = {
        data:[]
      }
      componentDidMount(){
          const keyword=localStorage.getItem('keyword');
          const url=`http://ec2-13-233-199-251.ap-south-1.compute.amazonaws.com/api/keyword/${keyword}`;
          console.log(url);
          axios.get(url)
          .then(res => {
            this.setState({data:res.data.Republic
            });
            console.log(res.data);
        });

      }
  render() {
    return (
      <div>
        <h1>{localStorage.getItem('keyword')}</h1>
        <Show data={this.state.data} /> 
      </div>
    )
  }
}

显示组件:

 class Show extends Component {
  render() {
    return (
        <div>
            <div>
                {this.props.data.map(({headline,link,date }, index) => 
                    <div key={index}>
                        <div>
                            <h3><a href={link}>{headline}</a></h3> 
                            <h6>{date}</h6>           
                        </div>
                    </div>
                 )}   
        </div>  
           <br></br>
            </div>
    )
  }
}

export default Show;

从上面的代码中,我正在获得仅Republic数组的标题链接。但是我想为数组中的所有索引(例如Ndtv,Indiatv和The Hindu)编写代码。

我是前端开发的新手。请帮我如何显示来自API的所有数据。

1 个答案:

答案 0 :(得分:2)

您必须遍历对象以呈现数据,这是您的处理方法。

将整个数据对象保存到状态(而不仅仅是共和国)

class KeywordNews extends Component {
    state = {
        data:{}
      }
      componentDidMount(){
          const keyword=localStorage.getItem('keyword');
          const url=`http://ec2-13-233-199-251.ap-south-1.compute.amazonaws.com/api/keyword/${keyword}`;
          console.log(url);
          axios.get(url)
          .then(res => {
            this.setState({data:res.data
            });
            console.log(res.data);
        });

      }
  render() {
    return (
      <div>
        <h1>{localStorage.getItem('keyword')}</h1>
        <Show data={this.state.data} /> 
      </div>
    )
  }
}

现在在Show组件中循环该对象

class Show extends Component {
  constructor(props) {
    super(props)
  }
  RenderData = () => {
    const { data } = this.props;
    return Object.keys(data).map((key) => {
      return (
        <div key={key}>
        { data[key].map(({headline, date, link}, index) => {
          return (
            <div key={index}>
              <h1> Chanel: {key} </h1>
              <h3> Headline: {headline} </h3>
              <h4> Date: {date} </h4>
            </div>
          )
        })}


          <br/>
          <br />
        </div>
      )
    }
    );
  }

  render() {
    const { RenderData } = this;
    const { data } = this.props;

    return (
      <div>
        {data && <RenderData />}
       </div>
    )
  }
}