【问题标题】:Showing all the results of news api in react在反应中显示新闻api的所有结果
【发布时间】:2019-02-07 01:55:44
【问题描述】:

我是 React 新手,我正在使用新闻 API 获取数据,我想显示所有结果,但我不知道该怎么做。我只能使用以下代码显示一个结果:

 if (country && data.cod !== '404')
 {
        const noa = data.totalResults
        console.log("the value is",noa)
        this.setState({
          Author: data.articles[0].author,
          Title: data.articles[0].title,
          Description: data.articles[0].description,
          Imageurl: data.articles[0].urlToImage,
          Publishedat: data.articles[0].publishedAt,
          Content: data.articles[0].content,
          error: ''
       })
 } 

 render() { 
    return (
      <div className='wrapper'>
         <Form getWeather={this.getWeather}>
            <Data
                Author={this.state.Author}
                Title={this.state.Title}
                Description={this.state.Description}
                Imageurl={this.state.Imageurl}
                Publishedat={this.state.Publishedat}
                Content={this.state.Content}
                error={this.state.error}
              />
          </Form>
       </div>
    );
  }
}

【问题讨论】:

    标签: reactjs api


    【解决方案1】:

    如果新闻 API 响应在一个数组中有多个项目,您将需要像这样重塑您的状态对象:

    state = { articles: [] } // default state
    

    然后您将使用setState 使用响应对象更新文章数组,如下所示:

    this.setState({ articles: data.articles })
    

    在您的渲染函数中,不是只显示一个&lt;Data /&gt; 组件,而是通过映射this.state.articles 来渲染多个,如下所示:

    render() {
      return (
        <div className='wrapper'>
          <Form getWeather={this.getWeather} />
          {this.state.articles.map(article => (
            <Data
              key={/*use something unique like article id here*/}
              Author={article.author}
              Title={article.title}
              Description={article.description}
              Imageurl={article.urlToImage}
              Publishedat={article.publishedAt}
              Content={article.content}
            />
          ))}
        </div>
      )
    }
    

    应该这样做。

    【讨论】:

    • noa 存储了那里的文章数量,我有什么办法可以用它来形成一种循环来显示所有结果!抱歉,我真的很陌生。
    • @ParamdeepSaini 在上面的示例代码中,有一个循环遍历结果。一般来说,您是 javascript 新手吗?数组映射方法循环遍历文章数组中的所有项目。
    • @ParamdeepSaini 如果此答案解决了您的问题,您应该将其标记为正确答案。
    • @jayarjo 我相信您对我的答案的编辑有一些错误。响应中每个文章对象的属性应为小写。
    • 我也认为&lt;Form/&gt; 元素有问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 2012-03-29
    • 2016-04-02
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多