react 代码编写原则

by Nirmalya Ghosh

由Nirmalya Ghosh

如何编写易读的React代码— 10种编码风格技巧 (How to write highly readable React code — 10 coding style tips)

When doing code reviews, developers rarely get enough time to truly understand each line of code we’re reviewing. Instead, we have to quickly ponder the different situations where that code might fail.

在进行代码审查时,开发人员很少有足够的时间来真正理解我们正在审查的每一行代码。 相反,我们必须快速考虑该代码可能失败的不同情况。

So every time I review code, I look for certain points to help me quickly understand the code.

因此,每次查看代码时,我都会寻找某些要点来帮助我快速理解代码。

This article will help you understand how you can write better code, so that other developers can better understand it. This article will give you a quick introduction to certain techniques I use while designing my components, and show you how you can do the same.

本文将帮助您了解如何编写更好的代码,以便其他开发人员可以更好地理解它。 本文将为您快速介绍我在设计组件时使用的某些技术,并向您展示如何做到这一点。

Note that we’ll stick mostly to ReactJS here, but that some of these points which may apply to using other JavaScript libraries as well.

请注意,这里我们将主要坚持使用ReactJS,但是其中一些要点也可能适用于使用其他JavaScript库。

提示1:请始终使用道具类型来定义组件中的所有道具 (Tip 1: Always use prop-types to define all the props in your components)

prop-types is runtime type checking for React props and similar objects.

prop-types是对React props和类似对象的运行时类型检查。

prop-types will help you check if the desired type of prop is getting passed into your component or not.

prop-types将帮助您检查所需的prop类型是否传递到组件中。

If the proper type of a specific prop is not passed into your component, then the package will throw a warning in the console of your browser.

如果特定属性的正确类型没有传递到您的组件中,则该包将在浏览器的控制台中引发警告。

In the above pen, you can check the console and it will throw the following warning:

在上面的笔中,您可以检查控制台,它将引发以下警告:

"Warning: Failed prop type: Invalid prop `message` of type `string` supplied to `Hello`, expected `array`.    in Hello"

From the above warning message, it is pretty clear that we are passing a string to the Hello component but the component expects the prop message to be of type array.

从上面的警告消息中,很明显,我们正在将字符串传递给Hello组件,但是该组件希望prop消息的类型为array。

提示2:使用displayName为组件定义一个特定名称 (Tip 2: Use displayName to define a particular name to your component)

The displayName string is used in debugging messages.

displayName字符串用于调试消息。

If you don’t use displayName in your components, you should use it from now on.

如果您的组件中未使用displayName,则应立即使用。

Normally, if you debug your component using the React developer tools, you will see the components because it’s inferred from the name of the function or class that defines the component.

通常,如果使用React开发人员工具调试组件,则会看到这些组件,因为它是从定义该组件的函数或类的名称推断出来的。

However, if you have a situation, where you have two components with the same name (button, dropdown, etc.), then you might need to rename your components. Otherwise, you won’t be able to distinguish between them.

但是,如果遇到这种情况,您有两个具有相同名称的组件(按钮,下拉列表等),则可能需要重命名组件。 否则,您将无法区分它们。

You can solve the above problem using displayName.

您可以使用displayName解决上述问题。

You simply rename one of the components using displayName.

您只需使用displayName重命名组件之一。

In the above example, you can see that even though the name of the class is Component, you will see the name “Hello” in the React developer tool because it has Hello as its displayName.

在上面的示例中,您可以看到,即使该类的名称是Component,您也将在React开发人员工具中看到名称“ Hello”,因为它的显示名是Hello。

This is very useful for debugging purposes and is often over-looked.

这对于调试目的非常有用,并且经常被忽略。

提示3:使用lint使代码更易于查看 (Tip 3: Use a linter to make your code easier to review)

If you care about your sanity, then you should use a linter on your codebase.

如果您关心自己的理智,那么应该在代码库上使用lint。

Linters will help you make your code similar to other fellow developers in your company. By follow a strict set of rules, you can be certain that the whole code base will be consistent.

Linters将帮助您使代码与公司中的其他开发人员相似。 通过遵循一组严格的规则,您可以确定整个代码库是一致的。

For instance, you can force other developers to use semicolons at the end of a line. If they don’t, then the linter will throw an error or a warning based on your settings.

例如,您可以强制其他开发人员在行尾使用分号。 如果不这样做,则短​​绒棉将根据您的设置抛出错误或警告。

The linter which I follow mostly is ESLint but you can choose anyone that suits your needs.

我主要关注的短毛绒是ESLint,但是您可以选择任何适合您需求的人。

提示4:在创建提取请求之前,请先检查自己的代码 (Tip 4: Review your own code before creating a pull request)

Whether you are fixing a bug or developing a new feature, chances are that you’ll push your changes and create a pull request quickly when you’re in a hurry.

无论您是要修复错误还是要开发新功能,都可能在急忙时快速推送更改并快速创建请求请求。

The problem with that is you don’t even get to review your own changes. As a result, you might miss some places which you can refactor and make it better.

这样做的问题是,您甚至无法查看自己的更改。 结果,您可能会错过一些可以重构并改善的地方。

From my experience, after reviewing my own changes, sometimes, I could make it more performant, split bigger functions into multiple smaller ones and make the code more modularised.

根据我的经验,有时在回顾自己的更改后,我可以使其性能更高,将较大的功能拆分为多个较小的功能,并使代码更加模块化。

Earlier, I never used to review my own code. But practicing this habit, I feel that it improves my coding and it might help you too.

以前,我从未使用过自己的代码。 但是练习这个习惯,我觉得它可以改善我的编码,也可能对您有帮助。

提示5:初稿并不总是最好的 (Tip 5: Your first draft is not always the best one)

Many of you already know this. The first iteration is not always the best one.

你们中的许多人已经知道这一点。 第一次迭代并不总是最好的。

You should look at your first iteration of coding and think about the features that you might have missed.

您应该查看第一次编码迭代,并考虑一下您可能会错过的功能。

One way to fix this could be doing a Test Driven Development (TDD), which is a great practice but is seldom followed. If you follow a TDD approach, you first iteration can be the best one. But you should look for a better approach.

解决此问题的一种方法可能是进行测试驱动开发(TDD),这是一个好习惯,但很少遵循。 如果遵循TDD方法,则第一次迭代可能是最好的方法。 但是您应该寻找更好的方法。

Take your time to think about how you want to proceed even before writing a single line of code and when you’re done with implementing a feature or fixing a bug, look at your changes and think how you can make it better.

花一些时间思考甚至在编写一行代码之前如何继续进行,以及在完成功能或修复错误之后,查看所做的更改,并思考如何将其改进。

提示6:将您的代码拆分为多个较小的函数 (Tip 6: Split your code into multiple smaller functions)

Splitting your bigger functions into multiple smaller functions will make the smaller functions more reusable. They will also become much easier to test.

将较大的功能拆分为多个较小的功能将使较小的功能更可重用。 它们也将变得更容易测试。

You can also create many utility files which can help you remove duplicate code from multiple files.

您还可以创建许多实用程序文件,这些文件可以帮助您从多个文件中删除重复的代码。

After creating multiple files, look at them and you will see that there are many duplicated lines of code. You can take these lines are create a utility file. You can then reuse the same utility file across multiple files.

创建多个文件后,查看它们,您将看到有很多重复的代码行。 您可以将这些行都创建一个实用程序文件。 然后,您可以跨多个文件重用同一实用程序文件。

提示7:创建多个文件,而不是编写大文件 (Tip 7: Create multiple files instead of writing a big file)

Reviewing one big file is always harder than reviewing multiple smaller files.

复查一个大文件总是比复查多个小文件更难。

If you split your code into multiple smaller files and each file contains only one logic, then it becomes very easy for the reviewer to review that file.

如果将代码分成多个较小的文件,并且每个文件仅包含一个逻辑,那么审阅者就很容易查看该文件。

提示8:命名文件时请务必小心 (Tip 8: Be very careful while naming your files)

Another thing you should remember here is that if you name your files according to the job that they perform, it will also help you in the future as well as other developers to understand what the file actually does.

您在这里还应该记住的另一件事是,如果您根据文件执行的工作来命名文件,这也将在将来帮助您以及其他开发人员了解文件的实际作用。

After looking at the name of the file, other developers should understand what the file is supposed to do.

在查看了文件名之后,其他开发人员应了解该文件应该做什么。

For instance, dropdown.js is a good name but it’s very generic and if you use it in multiple places in the same directory, you might name it like topDropdown.js, bottomDropdown.js, which is bad.

例如,dropdown.js是一个好名字,但它非常通用,如果在同一目录中的多个位置使用它,则可能将其命名为topDropdown.js,bottomDropdown.js,这很糟糕。

A better way will be to prefix them with the job that they are supposed to perform. For instance, userDropdown.js, fileDropdown.js, etc.

更好的方法是为他们添加应该执行的工作。 例如,userDropdown.js,fileDropdown.js等。

提示9:始终为您的代码编写测试 (Tip 9: Always write tests for your code)

I can’t stress enough the importance of this point. Tests complete your code.

我不能太强调这一点的重要性。 测试完成您的代码。

After developing a feature, you might feel that it works and it does work. But there can be (and most probably will) edge cases where it might not work. Tests will help you identify those cases.

开发功能后,您可能会觉得它确实有效。 但是在某些情况下(可能很可能会),它可能不起作用。 测试将帮助您识别这些情况。

It’s obvious that writing test cases will increase the time that you need to write your code. But, it will always help you eliminate potential bugs that might crop up in the future.

显然,编写测试用例会增加编写代码所需的时间。 但是,它将始终帮助您消除将来可能出现的潜在错误。

You should take the time to write tests if you care about your application.

如果您关心应用程序,则应该花时间编写测试。

技巧10:不要过度使用错误处理生命周期挂钩 (Tip 10: Don’t over-use the error handling lifecycle hook)

React 16 introduced a better way of handling errors using a feature called Error Boundaries.

React 16引入了使用称为错误边界的功能来处理错误的更好方法。

Essentially, error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.

本质上,错误边界是React组件,可在其子组件树中的任何位置捕获JavaScript错误,记录这些错误,并显示后备UI,而不是崩溃的组件树。

If the logic for the fallback UI is present in your ErrorBoundary component, then you can encapsulate your component inside that ErrorBoundary component.

如果您的ErrorBoundary组件中存在后备UI的逻辑,则可以将您的组件封装在该ErrorBoundary组件中。

<ErrorBoundary>  <YourComponent /></ErrorBoundary>

This is a nice way in which you can show a fallback UI for your errors. But you don’t need to wrap all your components with an ErrorBoundary component.

这是显示错误的备用用户界面的一种好方法。 但是,您不需要使用ErrorBoundary组件包装所有组件。

You can put your ErrorBoundary component only in a few strategic places where you need them.

您只能将ErrorBoundary组件放在需要它们的几个重要位置 。

结论 (Conclusion)

I hope that these points will help you write better ReactJS code and betterJavaScript code in general. Let me know if you use some more approaches that I missed here.

我希望这些观点能帮助您总体上编写更好的ReactJS代码和更好JavaScript代码。 让我知道您是否使用了我在这里错过的其他方法。

翻译自: https://www.freecodecamp.org/news/10-points-to-remember-thatll-help-you-master-coding-in-reactjs-library-d0520d8c73d8/

react 代码编写原则

react 代码编写原则_如何编写易读的React代码— 10种编码风格技巧相关推荐

  1. 编写代码的软件用什么编写的_团队编写代码

    编写代码的软件用什么编写的 Software is rarely written in a silo. Whether you're building the next social media ap ...

  2. 编写代码的软件用什么编写的_当编写过多的代码可能会杀死您

    编写代码的软件用什么编写的 因此,既然我以这个挑衅性的标题吸引了您,我想我需要澄清一下. 是的,这是真的. 太多的编码会杀死您,真正的问题是"原因是什么?" 答案是: 慢性压力. ...

  3. java代码重构原则_重构原则

    重构原则 重构:对软件内部结构的一种调整,目的是在不改变软件客观察行为的前提下,提高其可理解性,降低修改成本. 何为重构 重构改进软件的设计.如果没有重构,程序的设计会逐渐腐败变质.而改进设计的一个重 ...

  4. 软件工程流程图编写软件_如何编写杀手级软件工程简历

    软件工程流程图编写软件 对简历的深入分析使我在Google,Facebook,亚马逊,微软,苹果等公司接受了采访. (An in-depth analysis of the résumé that g ...

  5. react 组件封装原则_我理解的React:React 到底是什么?

    希望本文能帮助没接触过 React 的同学,对React有个大致的理解. 最近要做一个"前端零基础的入门课程分享",很多非前端同学可能只是知道 React 是个前端框架,整体对 R ...

  6. react文字滚动插件_【赠书】Preact(React)核心原理详解

    豆皮粉儿们,又见面了,今天这一期,由字节跳动数据平台的"winge(宝丁)",带大家见识见识前端"轮子"之一Preact框架. 提到Preact,你肯定会先想到 ...

  7. python代码写名字_必知必会系列_python代码优雅之道之代码命名约定

    代码的命名约定对代码的提高可读性影响巨大.本文中,我们将总结并向您提供一些关于命名的最佳实践的示例,以帮助您编写更优雅的Python代码,使将来可能阅读和使用您的代码的人(包括您自己)受益. Pyth ...

  8. pycharm 查看代码行数_【收藏】提高PyCharm效率的10个小技巧

    PyCharm是最常用的python开发IDE,程序员可以通过PyCharm强大的功能节约大量时间用来 摸鱼 工作,提高生产效率. 阿狗总结了10个自己会用到的PyCharm中可以提高撸码效率的小技巧 ...

  9. 压缩过的js代码怎么还原_码农晒出一段代码:500行代码没有一字注释,这种情况怎么应对?...

    对于程序员经常提到的"代码",从某种程度上来讲就算是机器码,因为这个东西机器很擅长读,不论写的怎么乱,怎么压缩混淆,在机器看来都是一样的,而人就不一样了,哪怕是能力再强的程序员,代 ...

最新文章

  1. 如何使用Openfiler为VMware ESX设置一个免费的iSCSI或NAS储存系统
  2. c/c++ 标准库 插入迭代器 详解
  3. please wait while windows configures microsoft visual studio professional 2013
  4. DNS服务器之简单配置(一)
  5. 如何才能写出一手高质量优美的代码
  6. html5 XMLHttpRequest 图片异步上传
  7. boost::hana::greater_equal用法的测试程序
  8. [linux] 多进程和多线程
  9. UI组件库从1到N开发心得-组件篇
  10. 18_python基础—面向对象-多态
  11. 使用依赖注入的ASP.NET Core 2.0用户角色基础动态菜单管理
  12. 1017. A除以B (20)-PAT乙级真题
  13. macos 字体_巧用 iTerm2 zsh oh-my-zsh 打造炫酷的 MacOS 终端环境
  14. vue企业门户网站模板_门户网站建设费用需要多少钱?
  15. fir.im Weekly - 从零开始创建 Android 新项目
  16. 图书信息管理系统设计与实现c语言,图书信息管理系统设计(c语言)
  17. 电子邮箱地址怎么填?如何登陆电子邮箱地址?
  18. golang下文件锁的使用
  19. Java毕设-商标管理系统
  20. 家用空气净化器除甲醛什么品牌好 能除甲醛吗

热门文章

  1. 对象交互 空调与摇控器 0107
  2. 未来机器人哆拉A梦身上的高科技程序应用
  3. javascript-流程控制-循环-分支-三元运算符
  4. Mysql查看某个表大小
  5. MNS消息服务计费处理参考
  6. Facebook黄毅博士:像加工艺术品一样构建技术产品
  7. OSPF的高级应用之地址汇总与虚链路的配置
  8. 【Hadoop Summit Tokyo 2016】云上的大象
  9. Symantec Backup Exec 2014 备份Exchange 2013之二安装主备服务器
  10. (转)实现自己的http server