首页 > 解决方案 > 你如何从 React 中的 api 渲染?

问题描述

我已经使用 NASA 的 api 成功地改变了状态。现在我想显示来自 api 的标题、图像和解释。我是初学者,所以放轻松!

我试过搜索并尝试不同的代码,但没有成功。想知道这里是否有人可以阐明我做错了什么。

this.state = {
  picture: "",
  date: ""
};
componentDidMount(){
  fetch(`https://api.nasa.gov/planetary/apod?api_key=${API_KEY}`)
    .then(response => response.json())
    .then(json => this.setState({ picture: json }));
};
render(){
  return (
    <div className="container">
      <h1>NASA Picture of the Day</h1>
      <form onSubmit={this.handleSubmit}>
        (YYYY-MM-DD):
        <input
          type="text"
          id="date"
          placeholder="input date"
          value={this.state.date}
          onChange={this.handleChange}
        />
        <button type="submit" disabled={!this.state.date}>
          Submit
        </button>
      </form>
    </div>
  );
};

标签: reactjs

解决方案


目前来自 NASA API 的示例响应如下:(不确定将来是否会更改)

{
"date": "2019-08-04",
"explanation": "Twenty-one years ago results were first presented indicating that most of the energy in our universe is not in stars or galaxies but is tied to space itself.  In the language of cosmologists, a large cosmological constant -- dark energy -- was directly implied by new distant supernova observations.  Suggestions of a cosmological constant were not new -- they have existed since the advent of modern relativistic cosmology. Such claims were not usually popular with astronomers, though, because dark energy was so unlike known universe components, because dark energy's abundance appeared limited by other observations, and because less-strange cosmologies without a signficant amount of dark energy had previously done well in explaining the data. What was exceptional here was the seemingly direct and reliable method of the observations and the good reputations of the scientists conducting the investigations. Over the two decades, independent teams of astronomers have continued to accumulate data that appears to confirm the existence of dark energy and the unsettling result of a presently accelerating universe. In 2011, the team leaders were awarded the Nobel Prize in Physics for their work.  The featured picture of a supernova that occurred in 1994 on the outskirts of a spiral galaxy was taken by one of these collaborations.    News: APOD is now available via Facebook in Hindi.",
"hdurl": "https://apod.nasa.gov/apod/image/1908/SN1994D_Hubble_2608.jpg",
"media_type": "image",
"service_version": "v1",
"title": "Rumors of a Dark Universe",
"url": "https://apod.nasa.gov/apod/image/1908/SN1994D_Hubble_960.jpg"
}

在同一组件中显示来自 NASA 的一些信息(假设您想在单击提交按钮之前显示详细信息)

let picture = this.state.picture;
 return (
      <div className="container">
        <h1>NASA Picture of the Day</h1>
        <h2>{picture.title}</h2>
        <img src={picture.url} alt={picture.title}></img>
        <p>{picture.explanation}</p>
         ___________ YOUR FORM INPUT CONTROLS _____________
      </div>
    );

推荐阅读