2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > 我如何使用React和Typescript在freeCodeCamp中构建天气应用

我如何使用React和Typescript在freeCodeCamp中构建天气应用

时间:2023-12-09 10:59:46

相关推荐

我如何使用React和Typescript在freeCodeCamp中构建天气应用

by Kelvin Mai

通过凯文麦

我如何使用React和Typescript在freeCodeCamp中构建天气应用 (How I built the weather app in freeCodeCamp using React and Typescript)

So I finally decided to come back to freeCodeCamp and try to finish out my Front End Development Certificate. I had already finished all the algorithms and tutorials earlier last year, and the only thing missing was the projects.

因此,我最终决定返回freeCodeCamp并尝试完成我的前端开发证书。 去年早些时候,我已经完成了所有算法和教程,唯一缺少的是项目。

But now that I have more experience as a Full Stack Developer, most of the projects are a bit easy for my current level. So I had two choices. I could either go back to the basics and finish them all in a day, or I could kill two birds with one stone: have some fun and experiment with technology while working on these projects. I opted for the latter.

但是,既然我有更多的全栈开发人员经验,就我目前的水平而言,大多数项目都比较容易。 所以我有两个选择。 我或者可以回到基础上并在一天内完成所有步骤,或者可以用一块石头杀死两只鸟:在进行这些项目时,可以玩得开心,可以尝试技术。 我选择了后者。

But let’s make that three birds — because I have been wanting to write a tutorial/guide thing for a while. Today, what we’re going to tackle is the Show The Local Weather project. But this time, it’s going to combine React and Typescript! You can take a look at the finished code in this GitHub repo, as well as a live demo here.

但是让我们把这三只鸟做成一只鸟-因为我一直想写一篇教程/指南的东西。 今天,我们要解决的是“ 显示当地天气”项目。 但是这次,它将结合React和Typescript! 您可以在此GitHub存储库中查看完成的代码,以及此处的实时演示。

背景(Background)

So first thing’s first: why would I want to do this? Well here’s the thing: I have been jumping back and forth with Angular 5 and React for a while now. And I like React more as a framework. It’s small and concise, but has all the features you need to create a fully functional Single Page Application. As for Angular, it is far too large for me to enjoy for an app as small as this…but it uses Typescript!

首先是第一件事:我为什么要这样做? 好了:我一直在使用Angular 5和React来回跳跃了一段时间。 我更喜欢React作为框架。 它虽然小巧简洁,但具有创建完整功能的单页应用程序所需的所有功能。 至于Angular,对于像这样小的应用程序来说,它太大了,我无法欣赏……但是它使用Typescript!

TypeScript is a super set of JavaScript that adds a lot of features that are just missing from JavaScript, even with the enhancements from ES6/7. It’s mostly known for it’s static typing. So I wondered if I could get the best of both worlds. The answer was a resounding YES!… Redux not included. (I mean youcaninclude Redux, but so far it’s been a pain to set up, so I won’t be doing it for this guide.)

TypeScript是JavaScript的超集,即使添加了ES6 / 7的增强功能,它也添加了JavaScript所缺少的许多功能。 它以静态类型而闻名。 所以我想知道我能否同时兼顾两者。 答案是肯定的!!不包括Redux。 (我的意思是您可以包括Redux,但到目前为止,设置起来很麻烦,因此在本指南中我不会这样做。)

For this project, we’re going to focus on the bare minimum of the User Stories, because my focus is the technology rather than any extra features. As such, the API we’ll be using for this app is going to be Wunderround. It’s perfect for what we’re building, because they offer temperatures in both Fahrenheit and Celsius and also provide icons for the different weather conditions. This means less programmatic work on our end.

对于本项目,我们将只关注最少的用户故事,因为我的重点是技术而不是任何其他功能。 因此,我们将为此应用程序使用的API是Wunderround 。 对于我们正在建造的建筑物来说,它是完美的选择,因为它们既提供华氏温度,又提供摄氏温度,并且还提供针对不同天气情况的图标。 这意味着我们这方面的编程工作会减少。

步骤0:设定 (Step 0: Set Up)

I’ll be usingcreate-react-appfor this project, with the custom React script for Typescript, so that we can keep the zero configuration and ease of use. A good article on setting up a React app with TypeScript was written by Trey Huffine and can be found here.

我将为该项目使用create-react-app以及用于Typescript的自定义React脚本,以便我们可以保持零配置和易用性。 Trey Huffine写了一篇有关使用TypeScript设置React应用程序的好文章,可以在这里找到。

I definitely suggest looking at that post for some more in depth set up. But without further ado, we are going to run the following line in the terminal.

我绝对建议您查看该帖子以进一步了解更多信息。 但是事不宜迟,我们将在终端中运行以下行。

create-react-app weather --scripts-version=react-scripts-tsnpm install --save core-decorators

I’ll get to the decorators a little later. Just know that it’s a neat little feature that I was really excited to try out. But to be able to use it, we’ll have to edit ourtsconfig.jsonfile to include experimental decorators. To do this, just add the bold line of code.

我待会再去装修。 只是知道这是一个很好的小功能,我真的很兴奋能尝试一下。 但是要使用它,我们必须编辑tsconfig.json文件以包含实验装饰器。 为此,只需添加粗体代码。

{ "compilerOptions": {// ...code hidden... "noUnusedLocals": true, "experimentalDecorators": true } // ...more code hidden...}

And since I have Prettier installed on my development environment, I had to change mytslint.jsonfile because the lint conflicted with the formatter. If you have a similar development set up, I suggest just deleting all the tslint rules so that you don’t have to get bogged down on configuration. The file should look like this after you’re done.

而且因为我更漂亮对我的开发环境中安装,我不得不改变我tslint.json文件,因为皮棉与格式冲突。 如果您进行了类似的开发,建议您删除所有的tslint规则,这样就不必陷入配置问题。 完成后,文件应如下所示。

The folder structure that I will be using will look like the following. You can create, delete, and move files accordingly.

我将使用的文件夹结构如下所示。 您可以相应地创建,删除和移动文件。

weather-app/├─ .gitignore├─ node_modules/├─ public/├─ src/ └─ assets/| - - loader.svg| - - logo.svg └─ components/| - - Weather.tsx| - - WeatherDisplay.tsx └─ styles/| - - App.css| - - WeatherDisplay.css | — — index.tsx | — — registerServiceWorker.ts | — — App.tsx | — — index.css | - - config.ts | - - types.ts├─ package.json├─ tsconfig.json├─ tsconfig.test.json└─ tslint.json

Okay, the worst is over! We have finally set up our app. Let’s dive into the code.

好吧,最糟糕的时期已经过去了! 我们终于建立了我们的应用程序。 让我们深入研究代码。

步骤1:样式 (Step 1: Styling)

I want to get the styling out of the way first. I’m not much of a designer, so all I really did was re-skin thecreate-react-appdefault styles to have the freeCodeCamp green theme. Additionally I made the button more button-like and of course, more green. You are free to go wild with this if you happen to be a CSS master. You can also download image files here and place them in yourassets/folder.

我想先取消样式。 我不是一个设计师,所以我真正要做的只是重新create-react-appcreate-react-app默认样式,使其具有freeCodeCamp绿色主题。 另外,我使按钮更像按钮,当然也更绿色。 如果您碰巧是CSS大师,则可以随意使用。 您也可以在此处下载图像文件,并将其放置在assets/文件夹中。

第2步:好的,我撒谎了……更多设置 (Step 2: Okay, I lied… More Set Up)

But don’t worry, it’s actual code this time. First let’s start with the easy part: adding your API and API keys. Nothing new here — it looks exactly like normal JavaScript so far.

但是不用担心,这是实际的代码。 首先让我们从简单的部分开始:添加您的API和API密钥。 这里没什么新鲜的-到目前为止,它看起来完全像普通JavaScript。

Now for the TypeScript specific thing, we have to specify types. Well, we don’t have to, but we definitely should. The reason behind static typing is that it gives us security. Unlike normal JavaScript, our code won’t run if things are of the wrong type. Essentially this means that the compiler just flat out won’t let us write bad code.

现在,对于特定于TypeScript的东西,我们必须指定类型。 好吧,我们没有必要,但是我们绝对应该。 静态类型背后的原因是它为我们提供了安全性。 与普通JavaScript不同,如果类型错误,我们的代码将无法运行。 从本质上讲,这意味着编译器只会让我们无法编写错误的代码。

As you can see, it’s not too scary. Just add the type after a colon. The primitive types (string, number, boolean) are supported out of the gate. With objects, it is a good idea to create a new type specific to that particular object as seen inWeatherDatawithDisplayLocation.

如您所见,它并不太吓人。 只需在冒号后面添加类型即可。 外边支持原始类型(字符串,数字,布尔值)。 对于对象,最好创建一个特定于该特定对象的新类型,如使用DisplayLocationWeatherData

Now, I was a little lazy, because the shape of the data coming from our API is a lot larger, and I could have created the whole object. But I opted to just take what I needed and discard the rest, which is why thistypes.tsfile is as small as it is.

现在,我有点懒了,因为来自我们的API的数据形状要大得多,而且我可以创建整个对象。 但是我选择了我需要的东西,而丢弃了其余的东西,这就是为什么types.ts文件是如此之小的原因。

第3步:做出React-有趣的部分 (Step 3: React — The Fun Part)

I’m going to skip over theindex.tsxandApp.tsxfiles because there’s really nothing really new there. Just know that the imports are different because of how strict TypeScript is about modules. Instead, we’re going to go over the presentational component first.

我将跳过index.tsxApp.tsx文件,因为那里确实没有什么新东西。 只是知道导入是不同的,因为TypeScript对模块的要求非常严格。 相反,我们将首先介绍演示组件。

I still prefer to destructureComponentandFragmentfrom React, instead of callingponent, as it reduces redundancy. And for Fragments, if you’ve never played with them before, it’s basically a div that doesn’t show up in the HTML markup.

我仍然更喜欢从React解构ComponentFragment,而不是调用ponent,因为它减少了冗余。 对于Fragments,如果您以前从未使用过它们,则基本上是一个div,不会在HTML标记中显示。

You will also notice that I have added interfaces at the top. An interface specifies what our props and state should look like. And if you haven’t noticed, TypeScript’s gimmick is adding types to everything, so that is what’s happening above within the angle brackets<Props, State>. If you are familiar with prop types, it does the same thing, but I feel like this is much cleaner.

您还将注意到,我在顶部添加了接口。 接口指定了我们的道具和状态。 而且,如果您没有注意到,TypeScript的花招就是为所有内容添加类型,因此,这就是尖括号<Props, State>中上面发生的事情。 如果您熟悉prop类型,它会做同样的事情,但是我觉得这要干净得多。

The next thing is the weird@symbol. Well, that’s a decorator! I originally wanted to hook up Redux and connect so that I can show a much more complicated version, but theautobindwill do for now.

接下来是@符号。 好吧,那是个装饰! 我最初想连接Redux并进行连接,以便可以显示更复杂的版本,但是autobind暂时可以使用。

A decorator is basically a function that wraps around the class and applies necessary attributes. It also allows us to useexport defaultat the top, which is just a personal preference of mine.

装饰器基本上是一个包装类并应用必要属性的函数。 它还允许我们在顶部使用export default,这只是我的个人喜好。

@decorateexport default Class {}

// is the same as

export default decorate(Class)

In this case autobind will, as the name entails, automatically bindthisto everything so we don’t have to worry about binding issues. And coming from a more Object Oriented language, these class methods will look a lot cleaner than the JavaScript work-around with the arrow functions.

在这种情况下autobind会,正如其名称限嗣继承,自动绑定this一切,所以我们没有关于绑定的问题担心。 而且,这些类方法来自一种更加面向对象的语言,看上去比带箭头功能JavaScript解决方法干净得多。

classMethod = () => { console.log('when you use arrows, you don't have to worry about the keyword "this"');}

classMethod () { console.log('because of javascript, you have to worry about the keyword "this" here');}

And now finally we move to the bulk of our logic, which is going to be living in theWeather.tsxcomponent.

现在,最后我们转到逻辑的大部分,它将Weather.tsxWeather.tsx组件中。

The first thing you’ll notice is the?in the interface. I mentioned that we definitely should define types for our props, but what happens when you know for certain it won’t be defined until after the API call? Well we can define optional types with a question mark.

您会注意到的第一件事是?在界面中。 我提到我们绝对应该为道具定义类型,但是当您确定要等到API调用之后才能定义它时,会发生什么情况? 好吧,我们可以用问号定义可选类型。

What is happening in the background is that the variableweatherDatais only allowed to be aWeatherDatatype or undefined. Also, remember that ourWeatherDatatype is only a subsection of what wunderground offers. Earlier I mentioned that we are only going to take the data that we needed from the API — well, that’s what that huge destructuring on line 55 is doing.

在后台发生的事情是,仅允许变量weatherDataWeatherData类型或未定义。 另外,请记住,我们的WeatherData类型只是Wunderground提供的内容的一部分。 之前我提到过,我们只会从API中获取所需的数据-好的,这就是第55行的巨大分解工作。

Did I mention you can specify expected return types of functions? That’s what is happening here withgetCurrentPosition, because I wanted to make sure that it returns a promise.

我是否提到过您可以指定函数的期望返回类型? 这就是getCurrentPosition在这里发生的事情,因为我想确保它返回一个诺言。

The reasoning here is that I didn’t want to callgetCurrentWeatheruntil after we had the correct geolocation, which means we’re dealing with asynchronous events. Async always means Promises, so that’s what’s going to happen.

这里的理由是,直到我们有了正确的地理位置之后,我才想调用getCurrentWeather,这意味着我们正在处理异步事件。 异步总是意味着Promises,这就是要发生的事情。

A word of warning: the native geolocation API does take a long time to get a result without passing in any options. I opted to not add options to it as it was giving me errors at the time.

提示:本地地理位置API确实需要很长时间才能获得结果,而无需传递任何选项。 我选择不添加选项,因为当时它给了我错误。

And I believe that is all the new things happening in this app because of TypeScript. Everything else should be familiar if you know React. But hopefully you can see the benefits of this superset, as it adds both security to our code as well as some nice super powers.

而且我相信,由于TypeScript的缘故,此应用程序中正在发生所有新的事情。 如果您了解React,其他所有事情都应该熟悉。 但是希望您能看到此超集的好处,因为它既增加了我们代码的安全性,又增加了一些不错的超能力。

步骤4:完成! (Step 4: Complete!)

You did it! You finished an app that shows the weather at your current position. And in doing so, you’ve covered a good chunk of TypeScript as well as incorporating it into React.

你做到了! 您完成了一个显示当前位置天气的应用程序。 这样做时,您涵盖了很多TypeScript并将其合并到React中。

Of course, there can definitely be improvements on this, like an option to search and show other locations. And the UI can definitely be worked on. But if you haven’t already finished the weather app on freeCodeCamp, you have already gone above and beyond on this assignment.

当然,在此方面肯定可以进行改进,例如可以搜索并显示其他位置。 UI绝对可以使用。 但是,如果您尚未在freeCodeCamp上完成气象应用程序,那么您已经超出了这项任务。

翻译自: /news/weather-in-react-and-typescript-4f774fc07be7/

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。