【问题标题】:How to show API data in react component?如何在反应组件中显示 API 数据?
【发布时间】:2019-10-06 05:03:28
【问题描述】:

这是我的 json 网址:

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
        }
    ],
}

我编写了以下代码来在我的反应组件中显示新闻 Source Republic、Ndtv、Zenews 的标题链接日期:

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;

从上面的代码中,我得到了只有共和国数组的标题链接。但我想为数组中的所有索引编写代码,例如 Ndtv、Indiatv、The Hindu。

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

【问题讨论】:

  • In componentDidMount 你只为共和国取数据 this.setState({data:res.data.Republic});
  • 是的,我应该为所有其他人做什么?
  • @imsaiful 不是分配republic,而是将整个数据获取到组件状态,然后迭代数据。所以它会像 this.state.data.republic.map()
  • 好的,我会这样做,但我应该怎么做,比如 Zeenews,ndtv 等。如果你只为组件写这个答案会更好。谢谢。

标签: javascript json reactjs api


【解决方案1】:

您必须遍历对象才能呈现数据,这是您的做法。

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

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>
    )
  }
}

【讨论】:

  • 感谢您的努力,但我得到的数据未在 Object.keys(data).map((key) 中定义
  • 我已经编辑了代码。我搞砸了const { data } = this.props;,它应该在RenderData 函数中。并且为了保持一致性,请将您的 data: [] 更改为 data: {},我在上面也进行了更改。
  • 现在得到未在此行定义的错误数据 {data && }
  • 我用 const { RenderData } = this;常量 { 数据 } = 这个;但没有得到任何标题或其他信息。这里是源文件链接github.com/imsaiful/save4thpillar/blob/master/save4thpillar/src/…
  • 我已经更新了代码。让我知道这是否有效。如果我们使用RenderData = () =&gt; {},则类级别this 关键字在函数范围内可用。
猜你喜欢
  • 2018-02-18
  • 2022-06-24
  • 1970-01-01
  • 2020-08-20
  • 1970-01-01
  • 2021-02-19
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
相关资源
最近更新 更多