我如何使用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 you can include 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 using create-react-app for 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 our tsconfig.json file 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 my tslint.json file 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 the create-react-app default 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 your assets/ 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 in WeatherData with DisplayLocation .

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

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 this types.ts file is as small as it is.

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

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

I’m going to skip over the index.tsx and App.tsx files 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 destructure Component and Fragment from React, instead of calling React.Component , 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 ,而不是调用React.Component ,因为它减少了冗余。 对于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, Sta te>中上面发生的事情。 如果您熟悉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 the autobind will 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 use export default at 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 bind this to 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 the Weather.tsx component.

现在,最后我们转到逻辑的大部分,它将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 variable weatherData is only allowed to be a WeatherData type or undefined. Also, remember that our WeatherData type 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 with getCurrentPosition , because I wanted to make sure that it returns a promise.

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

The reasoning here is that I didn’t want to call getCurrentWeather until 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上完成气象应用程序,那么您已经超出了这项任务。

翻译自: https://www.freecodecamp.org/news/weather-in-react-and-typescript-4f774fc07be7/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/394425.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

mysql结果集相减_MySQL_(Java)使用JDBC向数据库发起查询请求

课程相关链接&#xff1a;JDBC编程和MySQL数据库课程源代码在文章末尾~Java Database Connectivity简单来说就是使用Java里面提供的一些类和方法&#xff0c;利用程序链接数据库&#xff0c;进行增删改查操作。这个过程就叫做JDBC编程接下来我们便分五步通过JDBC对MySQL中的数据…

在双系统(Windows与Ubuntu)下删除Ubuntu启动项

问题概述&#xff1a;因为在自己学习Linux的时候&#xff0c;按照网上的教程错误的删除了Ubuntu的一个内核驱动&#xff0c;导致Ubuntu不能启动。我想到的办法是重新安装系统&#xff0c;重装系统的第一步便是将Ubuntu从电脑中卸载。该笔记是有关如何删除Ubuntu启动项的。 使用…

iangularjs 模板_2018-web前端的自我介绍-优秀word范文 (5页)

本文部分内容来自网络整理&#xff0c;本司不为其真实性负责&#xff0c;如有异议或侵权请及时联系&#xff0c;本司将立即删除&#xff01;本文为word格式&#xff0c;下载后可方便编辑和修改&#xff01;web前端的自我介绍篇一&#xff1a;个人总结的web前端面试题1、自我介绍…

Teradata QueryGrid整合最佳分析技术 拓展客户选择空间

ZDNET至顶网CIO与应用频道 05月11日 北京消息&#xff1a; 为持续帮助企业克服数据散布在不同分析系统的困难&#xff0c;全球领先的大数据分析和营销应用服务供应商Teradata天睿公司宣布对Teradata QueryGrid 进行重要技术升级。此次升级新增并强化六项QueryGrid技术&#xf…

神舟笔记本bios_海尔雷神(蓝天)神舟战神游戏本风扇狂转掉电大写灯狂闪维修实例...

昨天收到一台网友寄过来的海尔雷神游戏本。说到这个游戏本品牌&#xff0c;其实有几个品牌的笔记本&#xff0c;它们的主板和模具是一模一样的&#xff0c;也就是我们看到的品牌log不一样而已。比如神舟的战神 &#xff0c;机械师&#xff0c;机械革命&#xff0c;麦本本等等。…

Oracle 学习----:查看当前时间与Sqlserver语句不一样了

oracle:select sysdate from dual sqlserver: select getdate() ---------------------试试这个---------------------------------------------------------- insert into OracleTab values(sysdate) insert into SqlserverTab values(getdate())转载于:https://www.cnblogs…

react发送和接收请求_React行为编程简介:请求,等待和阻止

react发送和接收请求by Luca Matteis卢卡马蒂斯(Luca Matteis) React行为编程简介&#xff1a;请求&#xff0c;等待和阻止 (An intro to Behavioral Programming with React: request, wait, and block) Behavioral Programming (BP) is a paradigm coined in the 2012 artic…

leetcode96. 不同的二叉搜索树(动态规划)

给定一个整数 n&#xff0c;求以 1 … n 为节点组成的二叉搜索树有多少种&#xff1f; 解题思路 *数组含义&#xff1a;dp[i] i个节点的不同组成结构 状态转移&#xff1a;任取节点为根节点&#xff0c;遍历左右子树可能出现的个数,dp[i]dp[left]dp[right] 初始化&#xff1a…

“康园圈--互联网+校园平台“项目之成果展示及项目总结

一、总体效果&#xff08;ipad端截图&#xff09; 网站前台页面网站后台管理台页面二、前台访问链接&#xff08;用pc访问效果最佳&#xff09;&#xff1a;http://www.liangzhilin.cn:9100/kangyuanquan/ &#xff08;为保证数据安全&#xff0c;后台管理链接不对外公开&#…

ajax jq 图片上传请求头_Jquery ajaxsubmit上传图片实现代码

这是数月前的事情了&#xff0c;场景是这样的&#xff1a; 在进行图片上传的时&#xff0c;我发现开发人员使用的上传图片方式是Iframe 传统的 http post 来处理的。而且未建立统一上传函数。于是将代码改造了。心想来个ajax异步上传图片吧&#xff0c;这技术应该很老套了。于…

这个免费的交互式课程在一小时内学习JavaScript

JavaScript is the most popular programming language on the web. You can use it to create websites, servers, games and even native apps. So no wonder it’s such a valuable skill in today’s job market.JavaScript是网络上最流行的编程语言。 您可以使用它来创建网…

java中二进制怎么说_面试:说说Java中的 volatile 关键词?

volatile 这个关键字可能很多朋友都听说过&#xff0c;或许也都用过。在 Java 5 之前&#xff0c;它是一个备受争议的关键字&#xff0c;因为在程序中使用它往往会导致出人意料的结果。在 Java 5之后&#xff0c;volatile 关键字才得以重获生机。volatile 关键字虽然从字面上理…

类的详解

面向对象是一种编程方式&#xff0c;此编程方式的实现是基于对类和对象的使用。类是一个模板&#xff0c;模板中包装了多个“函数”供使用&#xff08;可以讲多函数中公用的变量封装到对象中&#xff09;。对象&#xff0c;根据模板创建的实例&#xff08;即对象&#xff09;&a…

leetcode279. 完全平方数(动态规划)

给定正整数 n&#xff0c;找到若干个完全平方数&#xff08;比如 1, 4, 9, 16, …&#xff09;使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。 示例 1: 输入: n 12 输出: 3 解释: 12 4 4 4. 解题思路 数组含义&#xff1a;dp[i]数字i对应组成和的完全平方…

什么情况不能办理房产抵押贷款 房产抵押贷能贷多少?

所谓房产抵押贷款是指以自己或亲友的房产作为抵押物向贷款机构申请贷款&#xff0c;款项可用于企业经营、买房、买车、装修及其他用途的融资方式。但是有些情况是规定不能申请房产抵押贷款的&#xff0c;而且贷款的数额是有限的&#xff0c;不是想贷多少就多少。那么&#xff0…

Android RecyclerView 二级列表实现

Android RecyclerView 二级列表实现

2数据库表增加一个字段_14个实用的数据库设计技巧!

1. 原始单据与实体之间的关系可以是一对一、一对多、多对多的关系。在一般情况下&#xff0c;它们是一对一的关系&#xff1a;即一张原始单据对应且只对应一个实体。在特殊情况下&#xff0c;它们可能是一对多或多对一的关系&#xff0c;即一张原始单证对应多个实体&#xff0c…

错误: 找不到或无法加载主类 helloworld_全面剖析虚拟机类加载机制

1.引言java源文件经过编译后生成字节码class文件&#xff0c;需要经过虚拟机加载并转换成汇编指令才能执行&#xff0c;那么虚拟机是如何一步步加载这些class文件的对于java程序员是完全透明的&#xff0c;本文尝试全面分析jvm类加载机制。2.思考开始之前我们来简单思考一下&am…

nginx反向代理和shiro权限校验产生的404问题

问题描述: 我们的项目A&#xff08;以下简称A&#xff09;用了shiro做权限校验&#xff0c;nginx做反向代理&#xff0c;在另一个项目B&#xff08;以下简称B&#xff09;中点击某个A的链接时实现单点登录并会跳转到该路径。跳转到原路径的时候nginx报了404。出现404之后再次点…

android 揭示动画_如何使用意图揭示函数名称使代码更好

android 揭示动画Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority!“发现功能JavaScript”被BookAuthority评为最佳新功能编程书籍之一 &#xff01; Code is a way to communicate with developers reading it…