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

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 代码编写原则

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值