stellar js_在10分钟内制作一个Stellar React + NASA App

stellar js

One of the most stellar open API's out there is the NASA Astronomy Picture of the Day. In today's article, we are going to mess around with that API and build an application that displays the photo of the day, the title of that photo, the current date, and some information about the picture.

目前最出色的开放API之一是《 NASA天文图片》 。 在今天的文章中,我们将使用该API,并构建一个应用程序来显示当天的照片,该照片的标题,当前日期以及有关该图片的一些信息。

我们将要建设的 ( What We Will Be Building )

Using the NASA Open API: Astronomy Picture of the Day (APOD), we will be building an application that displays the information that is provided by that API. The information we will display is:

使用NASA Open API:每日天文图片(APOD),我们将构建一个显示该API提供的信息的应用程序。 我们将显示的信息是:

  • The photo

    照片
  • The photo's title

    照片的标题
  • Current date

    当前日期
  • Information on the photo

    照片信息

We will be building our application with React. More specifically, we will be using the React Router and even throw in a .env file for our API key. We are going to start from a new environment, but if you would like to look at the finished code now, please visit this GitHub repo.

我们将使用React构建我们的应用程序。 更具体地说,我们将使用React Router ,甚至将.env文件.env API密钥。 我们将从一个新环境开始,但是如果您现在想看一下完成的代码,请访问此GitHub存储库

什么是React Router? (What is the React Router?)

The react router is React's way of navigating around an application. We are able to change pages waiting having to load each page. We will build a Single Page Application (SPA) so even though it looks like we have multiple pages, we have one that is split into sections.

react路由器是React在应用程序中导航的方式。 我们能够更改页面,等待加载每个页面。 我们将构建一个单页应用程序(SPA),因此即使看起来我们有多个页面,我们也会将其分为多个部分。

Those sections, or components as we like to call them, can be navigated to depending on what the URL says. The React Router has us add to the URL to specify which component we are viewing. Generally, the Home page is declared with / and if we were to add an About page, we could do something like /about.

可以根据URL的内容导航到那些部分或我们喜欢称呼的组件。 React Router让我们添加到URL中以指定我们正在查看的组件。 通常,主页用/声明,如果要添加About页面,我们可以做类似/about事情。

In our app that we build, we will be using the following parts of the React Router:

在我们构建的应用程序中,我们将使用React Router的以下部分:

  1. BrowserRouter - How we tell our browser that we are going to be setting routes

    BrowserRouter-我们如何告诉浏览器我们将要设置路由
  2. Route - Matching up a component with the URL path we assign it to

    路线-将组件与我们为其分配的URL路径匹配
  3. Link - Using those URL path's to already assigned components

    链接-使用这些URL路径访问已分配的组件

NASA的开放API ( NASA's Open API )

Before we dive into the code, let's chat a little bit about setting up our API. If we were to head to { NASA's API } page we would find all the information about all of NASA's open APIs. Scroll down to where it says "Browse APIs" and we will see the API we want to use, "APOD: Astronomy Picture of the Day":

在深入研究代码之前,让我们聊一些关于设置API的知识。 如果我们要转到{NASA's API}页面 ,则会找到有关所有NASA的开放API的所有信息。 向下滚动到显示“浏览API”的位置,我们将看到我们要使用的API,“ APOD:当天的天文图片”:

In this section, we will also see the example query:

在本节中,我们还将看到示例查询:

https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY

We will be using this. Where it says DEMO_KEY, we will need to replace that with our own API key. Let's go grab that!

我们将使用它。 上面写着DEMO_KEY ,我们需要用我们自己的API密钥替换它。 让我们去抓住它!

API密钥 (API Key)

On the same page, we are going to scroll up to the section that says, "Generate API Key". We can also click on "Generate API Key" in the nav bar at the top:

在同一页面上,我们将向上滚动到“生成API密钥”部分。 我们还可以点击顶部导航栏中的“生成API密钥”:

Fill in the required information. No need to do the "Application URL".

填写必填信息。 无需执行“应用程序URL”。

Once we have done that, we will receive an email with an API Key in that email. Hold onto that key.

完成此操作后,我们将在电子邮件中收到一封包含API密钥的电子邮件。 按住该键。

美国航空航天局API信息 (Nasa API Information)

So far we need the following things for our NASA API connection:

到目前为止,我们的NASA API连接需要以下条件:

  1. The following URL: https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY

    以下网址: https://api.nasa.gov/planetary/apod?api_key=DEMO_KEYhttps://api.nasa.gov/planetary/apod?api_key=DEMO_KEY
  2. Our individual API Key that was sent to our email.

    我们的个人API密钥已发送到我们的电子邮件中。

创建React应用 ( Creating the React App )

Now that we have all the information we will need to connect our application to the open NASA open API, let's start building out our application!

现在我们有了将应用程序连接到开放的NASA开放API所需的所有信息,让我们开始构建应用程序!

For today's example, we will be using the Terminal to run commands to get our application set up, get our application running, and add in dependencies. Open up the Terminal and navigate to the folder we would like our application to live.

对于今天的示例,我们将使用终端运行命令来设置应用程序,运行应用程序并添加依赖项。 打开终端并导航到我们希望我们的应用程序存在的文件夹。

Once there, we are going to be using the create-react-app command to get our application running. Run the following command:

到达那里之后,我们将使用create-react-app命令来使我们的应用程序运行。 运行以下命令:

npx create-react-app nasa-apod

The npx command will install and run the command create-react-app for us. The last part of that command is the name of our app. We are going to be naming our app nasa-apod, feel free to name it whatever.

npx命令将为我们安装并运行命令create-react-app 。 该命令的最后一部分是我们应用的名称。 我们将要命名我们的应用nasa-apod ,随意命名。

Once our app is created, we are going to run the following command to get into our project:

创建我们的应用程序后,我们将运行以下命令进入我们的项目:

cd nasa-apo

Open up the project in whichever text editor, for example, VS Code.

使用任何文本编辑器(例如VS Code)打开项目。

And to get our app running, we are going to run the command:

为了使我们的应用程序运行,我们将运行以下命令:

npm start

And head on over to localhost:3000 in any browser to see our default React start page.

然后在任何浏览器中转到localhost:3000 ,以查看默认的React起始页面。

Yay! Our React app is ready for us!

好极了! 我们的React应用已经为我们准备好了!

我们的组件 (Our Components)

Quickly, let's set up our components that will hold our code. Within the /src folder, create a folder named /components. With that folder, create three files:

很快,让我们设置包含代码的组件。 在/src文件夹中,创建一个名为/components的文件夹。 使用该文件夹,创建三个文件:

  1. /Home.js

    /Home.js
  2. /NasaPhoto.js

    /NasaPhoto.js
  3. /NavBar.js

    /NavBar.js

Let's start building!

让我们开始构建!

React路由器魔术! ( React Router Magic! )

Before we start building out each component, let's set up our App.js so that our app can have seamless routing. We will need to install the dependency. To do so, run the command:

在开始构建每个组件之前,让我们设置App.js以便我们的应用程序可以进行无缝路由。 我们将需要安装依赖项 。 为此,请运行以下命令:

npm install--save react-router-dom

Navigate to src/App.js and replace all the code in there with the following code:

导航到src/App.js并将其中的所有代码替换为以下代码:

// src/App.js

import React from "react";
import { BrowserRouter, Route } from "react-router-dom";
import Home from "./components/Home";
import NasaPhoto from "./components/NasaPhoto";
import "./App.css";

export default function App() {
  return (
    <BrowserRouter>
      <div className="app">
          <Route component={Home} path="/" exact />
          <Route component={NasaPhoto} path="/nasaphoto" />
      </div>
    </BrowserRouter>
  );
}

In here we see that we have imported the react-router-dom, our /Home and /NasaPhoto components, and set up the routing for that.

在这里,我们看到已经导入了react-router-dom/Home/NasaPhoto组件,并/NasaPhoto设置了路由。

For the react-router-dom dependency, we pulled out BrowserRouter and Route for our routing.

对于react-router-dom依赖性,我们为浏览器选择了BrowserRouterRoute

  • BrowserRouter will wrap around our declared routes.

    BrowserRouter将环绕我们声明的路由。
  • Route will help us build out our routes, what component the route will show, and how the URL route will look.

    Route将帮助我们建立路线,路线将显示的组成部分以及URL路线的外观。

We can give BrowserRouter an alias if we want. That would look like `{ BrowserRouter as Router }` in the import.

如果需要,我们可以给BrowserRouter一个别名。 看起来就像导入中的{{BrowserRouter as Router}}。

We will be getting an error right now in our localhost:3000 view! That's because we haven't put anything into our components. Let's work on those!

现在我们在localhost:3000视图中将出现错误! 那是因为我们没有在组件中放入任何东西。 让我们继续努力吧!

家庭组件 ( Home Component )

Our Home component is going to have a large clickable button that will take us to the other component that will display the NASA picture of the day.

我们的主页组件将具有一个大的可单击按钮,它将带我们转到另一个组件,该组件将显示当天的NASA图片。

Head to src/components/Home and add the following code:

转到src/components/Home并添加以下代码:

// src/components/Home.js

import React from "react";
import { Link } from "react-router-dom";

export default function Home() {

  return (
    <div className="home">
      <Link className="home-link" to="/nasaphoto" >See into the stars!</Link>
    </div>
  );
}

Remember how in App.js we assigned the route, /nasaphoto to the component, NasaPhoto? We are now using that assignment in this component. We don't need to tell the <Link> which component because that's already done!

还记得我们在App.js如何将路由/nasaphoto分配给组件NasaPhoto吗? 现在,我们在此组件中使用该分配。 我们不需要告诉<Link>哪个组件,因为已经完成了!

If we visit our browser at localhost:3000, we will see the words "See into the stars!" and nothing else. We may need to restart our server.

如果我们访问位于localhost:3000浏览器,则将看到“看到星星!”字样。 没什么 我们可能需要重新启动服务器。

NASA APOD组件 ( NASA APOD Component )

Let's have that /nasaphoto URL route show us something! And speaking of the NASA Photo, let's call our API!

让我们/nasaphoto URL路由向我们展示一些东西! 说到NASA照片,我们称之为API!

Navigate to our src/components/NasaPhoto.js file and paste in the following code:

导航到我们的src/components/NasaPhoto.js文件,并粘贴以下代码:

// src/components/NasaPhoto.js

import React, { useState, useEffect } from "react";

export default function NasaPhoto() {
  const [photoData, setPhotoData] = useState(null);

  useEffect(() => {
    fetchPhoto();

    async function fetchPhoto() {
      const res = await fetch(
                // we'll update the KEYHERE soon!
        `https://api.nasa.gov/planetary/apod?api_key=KEYHERE`
      );
      const data = await res.json();
      setPhotoData(data);
    }
  }, []);

  if (!photoData) return <div />;

  return (
    <div className="nasa-photo">
        <img
          src={photoData.url}
          alt={photoData.title}
          className="photo"
        />
      <div>
        <h1>{photoData.title}</h1>
        <p className="date">{photoData.date}</p>
        <p className="explanation">{photoData.explanation}</p>
      </div>
    </div>
  );
}

Let's walk through this code!

让我们来看一下这段代码!

We are using React Hooks so we see that for state, we have set it to null and later we set setPhotoData to the data we pull out of the API.

我们正在使用React Hooks,所以我们看到对于状态,我们将其设置为null ,然后将setPhotoData设置为从API中提取的数据。

In the return() we are using photoData to use each element of the API in an organized way. We are using:

return()我们使用photoData以有组织的方式使用API​​的每个元素。 我们正在使用:

  1. Photo URL - That is the photo itself.

    照片网址-照片本身。
  2. Photo Title - That will be used as our alt for the photo and the h1 on our page.

    照片标题-将用作我们页面上的照片和h1 alt
  3. Photo Date - This will be the current date because this API is the Astronomy Picture of the Day.

    拍照日期-这将是当前日期,因为此API是当天的天文图片。
  4. Photo Explanation - This will be a paragraph of information that NASA provides about the photo.

    照片说明-这将是NASA提供的有关照片的信息段。

处理媒体类型 (Handling the Media Type)

The API sometimes sends back a short video. So we want to be able to display that properly. If the media type is "image", we will return it as an image. If not, we will return the "image/video" in an <iframe />.

API有时会发送回短视频。 因此,我们希望能够正确显示它。 如果媒体类型为“图像”,我们将其作为图像返回。 如果没有,我们将在<iframe />返回“图像/视频”。

Update the <img> tag to look like this. We're using a JavaScript ternary operator to either show an image or a video.

更新<img>标记,如下所示。 我们正在使用JavaScript三元运算符来显示图像或视频。

{photoData.media_type === "image" ? (
  <img
    src={photoData.url}
    alt={photoData.title}
    className="photo"
  />
) : (
  <iframe
    title="space-video"
    src={photoData.url}
    frameBorder="0"
    gesture="media"
    allow="encrypted-media"
    allowFullScreen
    className="photo"
  />
)}

添加API密钥 (Adding an API Key)

If we look at this part of the component:

如果我们看一下组件的这一部分:

const res = await fetch(
    // we'll update the KEYHERE soon!
  `https://api.nasa.gov/planetary/apod?api_key=KEYHERE`
);

We can see the KEYHERE part of the fetch. We don't want our key pushed to any source control, in our case, GitHub. So let's go ahead and create a secure way to store our key!

我们可以看到fetchKEYHERE部分。 我们不希望将密钥推到任何源代码控制中,例如我们的GitHub。 因此,让我们继续并创建一种安全的方式来存储我们的密钥!

环境变量 (Environment Variables)

Remember earlier we generated an API key on the NASA API website? That should have been sent to our email address that we put in the form. Let's go grab that key!

还记得我们之前在NASA API网站上生成的API密钥吗? 那应该已经发送到我们在表格中输入的电子邮件地址。 让我们去拿那个钥匙!

In the source of our project, let's create a file called .env. In this file, put in the following information:

在我们项目的源代码中,我们创建一个名为.env的文件。 在此文件中,输入以下信息:

// .env

REACT_APP_NASA_KEY="YOUR KEY HERE"

Where it says, "YOUR KEY HERE" put your unique key that was emailed to you. Go to the .gitignore file and put .env in there. That way, when this is pushed to GitHub, it doesn't push that sensitive key.

上面写着"YOUR KEY HERE"将您唯一的钥匙发送给您。 转到.gitignore文件,并将.env放入其中。 这样,当将其推送到GitHub时,它不会推送该敏感密钥。

使用我们的钥匙 (Using Our Key)

Let's head back to our src/components/NasaPhoto.js file and update it so it uses our key. At the top of the file, below the imports, add the following line:

让我们回到src/components/NasaPhoto.js文件并更新它,以便它使用我们的密钥。 在文件顶部,导入下面,添加以下行:

const apiKey = process.env.REACT_APP_NASA_KEY;

React uses REACT_APP_ to know that it's using an environment variable. That is why we named our key, REACT_APP_NASA_KEY. That makes it so we don't have to import the .env file, it just knows!

React使用REACT_APP_知道它正在使用环境变量 。 这就是为什么我们将密钥命名为REACT_APP_NASA_KEY 。 这样就可以了,所以我们不必导入.env文件,它知道!

Further down in the file, update the following code:

在文件的最下方,更新以下代码:

const res = await fetch(
    // this https was updated with ${apiKey}
  `https://api.nasa.gov/planetary/apod?api_key=${apiKey}`
);

We are now pulling in the NASA APOD API. Let's go ahead and restart our server and head to localhost:3000. We should see something like this!

我们现在正在引入NASA APOD API。 让我们继续并重新启动服务器,然后转到localhost:3000 。 我们应该看到这样的东西!

The view will be different depending on the day!

视日期而定,视图会有所不同!

导航栏组件 ( NavBar Component )

Before we throw on styling for our two components, let's add a navigation bar to our NasaPhoto view. Navigate to our src/components/NavBar.js file. Paste in the following code:

在为我们的两个组件添加样式之前,让我们向NasaPhoto视图添加导航栏。 导航到我们的src/components/NavBar.js文件。 粘贴以下代码:

// src/components/NavBar.js

import React from 'react';
import { Link } from 'react-router-dom';

export default function NavBar() {
    return (
        <div className="navbar">
            <ul>
                <Link className="link" to="/" exact >Take Me Home</Link>
            </ul>
        </div>
    )
}

In here, we are creating a nav bar that will take the user back to the home page where it says, "See into the stars!"

在这里,我们正在创建一个导航栏,该导航栏将使用户返回主页,其中显示“看星星”。

But before this can show up, we will need to nest this component inside another one. We want it on the /nasaphoto route, so let's head to our src/components/NasaPhoto.js. We want the following line to be added to our import at the top of the file:

但是在此显示之前,我们将需要将此组件嵌套在另一个组件中。 我们希望在/nasaphoto路线上使用它,因此让我们进入src/components/NasaPhoto.js 。 我们希望将以下行添加到文件顶部的导入中:

import NavBar from "./NavBar";

Next, we want to use that import. In the return of the file, add above the first <div>:

接下来,我们要使用该导入。 在文件的返回中,在第一个<div>上方添加:

<NavBar />

Things will break. 😳Let's chat about that real quick.

事情会破裂。 real让我们快速聊聊。

React片段 (React Fragments)

In React, we may want to return multiple elements. Rather than wrapping elements in a <div> we can wrap it in a Fragment. That will look like this:

在React中,我们可能想返回多个元素。 与其将元素包装在<div>不如将其包装在Fragment中 。 看起来像这样:

return (
    <React.Fragment>
      <ChildA />
      <ChildB />
    </React.Fragment>
  );

And the short syntax version of this looks like:

简短的语法版本如下所示:

return (
    <>
      <ChildA />
      <ChildB />
    </>
  );

We are going to be using the short syntax way. Let's add that in our return() in the NasaPhoto.js file.

我们将使用简短的语法方式。 让我们在NasaPhoto.js文件的return()中添加它。

最终的NasaPhoto文件 ( Final NasaPhoto File )

After it's all said and done, let's look at our final product of the src/components/NasaPhoto.js file:

说完一切之后,让我们看一下src/components/NasaPhoto.js文件的最终产品:

// src/components/NasaPhoto.js

import React, { useState, useEffect } from "react";
import NavBar from "./NavBar";

const apiKey = process.env.REACT_APP_NASA_KEY;

export default function NasaPhoto() {
  const [photoData, setPhotoData] = useState(null);

  useEffect(() => {
    fetchPhoto();

    async function fetchPhoto() {
      const res = await fetch(
        `https://api.nasa.gov/planetary/apod?api_key=${apiKey}`
      );
      const data = await res.json();
      setPhotoData(data);
      console.log(data);
    }
  }, []);

  if (!photoData) return <div />;

  return (
    <>
    <NavBar />
    <div className="nasa-photo">
      {photoData.media_type === "image" ? (
        <img
          src={photoData.url}
          alt={photoData.title}
          className="photo"
        />
      ) : (
        <iframe
          title="space-video"
          src={photoData.url}
          frameBorder="0"
          gesture="media"
          allow="encrypted-media"
          allowFullScreen
          className="photo"
        />
      )}
      <div>
        <h1>{photoData.title}</h1>
        <p className="date">{photoData.date}</p>
        <p className="explanation">{photoData.explanation}</p>
      </div>
    </div>
    </>
  );
}

We should also see our navigation bar at the top of the route, /nasaphoto. If we click on "Take Me Home" it should take us back to the / route.

我们还应该在路线顶部/nasaphoto处看到导航栏。 如果单击“带我回家”,它应该带我们回到/路线。

造型我们的组件 ( Styling Our Components )

We are not going to go much into the styling of our components, but let's make our application look nice! We're bringing in a Google Font called Righteous. Feel free to choose your own if you want to switch it!

我们不会过多介绍组件的样式,但是让我们的应用程序看起来不错! 我们引入了一种名为RighteousGoogle字体 。 如果要切换,请随意选择!

Head to the App.css file and replace all the styling in there with this:

转到App.css文件,并用以下内容替换其中的所有样式:

// src/App.css

@import url('https://fonts.googleapis.com/css2?family=Righteous&display=swap');

body {
  font-family: 'Righteous', cursive;
  color: #d14f4f;
  line-height: 1.7;
  font-size: 19px;
  background-color: #222222;
  background-image: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23424242' fill-opacity='0.4'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
}

/_ navbar ---------- _/

.navbar {
  background-color: rgba(22, 22, 22, 0.8);
  display: flex;
  justify-content: center;
}

.link {
  color: #efefef;
  display: inline-block;
  padding: 3px 20px;
  font-size: 16px;
  text-decoration: none;
  transition: 0.3s ease all;
}

.link:hover {
  color: #f59494;
  transform: scale(1.1);
}

/_ nasa photo ---------- _/

.nasa-photo {
  display: flex;
  padding: 40px;
  margin: 0 auto;
  max-height: 100%;
}

.nasa-photo img {
  width: 50%;
  margin-right: 50px;
  object-fit: contain;
  max-height: 80vh;
}

.nasa-photo h1 {
  margin-top: 0;
  margin-bottom: 0;
}

.nasa-photo .date {
  margin-top: 0;
  margin-bottom: 30px;
}

.nasa-photo .explanation {
  color: #bbb;
}

@media (max-width: 1280px) {
  .nasa-photo {
    display: block;
  }

  .nasa-photo img {
    width: 100%;
    margin-right: 0;
    margin-bottom: 30px;
  }
}

.home {
  display: flex;
  height: 100vh;
  align-items: center;
  justify-content: center;
}

.home-link {
  font-size: 40px;
  background: #f59494;
  display: inline-block;
  padding: 40px 80px;
  color: #fff;
  border-radius: 50%;
  text-decoration: none;
  transition: 0.3s ease all;
  text-transform: uppercase;
}

.home-link:hover {
  border-radius: 5px;
  background: #e77171;
}

In our file, we have styled each component. Feel free to change colors, fonts, anything really to make it more your own!

在我们的文件中,我们为每个组件设置了样式。 随意更改颜色,字体,任何真正使它更属于您的东西!

我们完成的应用程序! ( Our Finished App! )

We may need to restart the server. If so, do that and return to localhost:3000. We should see the following view:

我们可能需要重新启动服务器。 如果是这样,请执行该操作,然后返回到localhost:3000 。 我们应该看到以下视图:

If we were to click on the giant button in the middle, we would be routed to this view:

如果我们单击中间的巨型按钮,则会转到以下视图:

结论 ( Conclusion )

The NASA APOD API is a fun one because it changes every single day. It would be fun to add this API to a project where you know visitors would like to see that updated image every time they view your website.

NASA APOD API很有趣,因为它每天都在变化。 将此API添加到项目中会很有趣,您知道访问者每次访问您的网站时都希望看到更新的图像。

Using React Routing, React Fragments, and even environment variables, we were able to build a pretty application with some stellar data from an API. Mess around with the styling, add this API call to an existing application, or just be happy with this app! We built something pretty cool together!

使用React RoutingReact Fragments甚至环境变量,我们能够使用API​​中的一些恒星数据构建漂亮的应用程序。 弄乱样式,将此API调用添加到现有应用程序中,或者对这个应用程序感到满意! 我们一起创造了一些很棒的东西!

翻译自: https://scotch.io/tutorials/make-a-stellar-react-nasa-app-in-10-minutes

stellar js

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值