redux代码_我从阅读Redux源代码中学到了什么

redux代码

by Anthony Ng

由Anthony Ng

我从阅读Redux源代码中学到了什么 (What I learned from reading the Redux source code)

I’ve always heard that reading code is a good way to expand your horizons as a developer.

我一直听说,阅读代码是扩大您作为开发人员的视野的好方法。

So I made a conscious decision to really dig deep into a well-written JavaScript library and learn as much as I could.

因此,我做出了一个明智的决定,要真正深入研究编写良好JavaScript库并尽可能多地学习。

I chose to look at Redux because it has a relatively small codebase.

我选择查看Redux是因为它的代码库相对较小。

This article won’t be a tutorial on Redux but rather tidbits that I learned by looking through their source code. If you’re interested in learning Redux itself, I highly recommend watching the Getting Started with Redux series from the creator of Redux himself, Dan Abramov.

本文将不是有关Redux的教程,而是我通过查看其源代码学到的花絮。 如果您有兴趣学习Redux本身,我强烈建议您观看Redux创始人Dan Abramov的Redux 入门系列。

向开源学习 (Learning from Open Source)

When new developers ask me what the best way of learning is, I respond that they should work on projects.

当新的开发人员问我最好的学习方法是什么时,我回答说他们应该从事项目。

It’s amazing when you come across a project idea to work on that you would actually use yourself. That passion for a product will get you through those multi-hour debug sessions, and prevent you from abandoning it when the going gets rough.

当您遇到一个可以真正使用自己的项目创意时,这真是太神奇了。 对产品的热情将使您度过这些长达数小时的调试会话,并防止您在事情变得艰难时放弃它。

But there’s a disadvantage in only working by yourself. You won’t notice any of the bad habits you pick up along the way. You won’t learn any best practices. You won’t hear about all of the new frameworks and tools that are sprouting around you. And you’ll quickly notice that your skills plateau during your lonely adventure.

但是仅靠自己一个人工作有一个缺点。 您不会注意到在此过程中遇到的任何不良习惯。 您不会学到任何最佳实践。 您将不会听到周围出现的所有新框架和工具。 您会很快注意到,在孤独的冒险中,您的技能处于稳定状态。

Whenever possible, I recommend you seek out others developers to pair program with.

只要有可能,我建议您寻找其他与程序配对的开发人员。

Sitting next to a peer (or if you’re lucky, someone more experienced) allows you to observe their thought processes. You get to see how their fingers glide over the keyboard. You get to watch how they struggle to tackle algorithms. You get to learn new developer tools and keyboard shortcuts. You get to soak in all the intangible things that you wouldn’t pick up working by yourself.

坐在同伴旁边(或者如果您很幸运,可以坐在更有经验的人旁边),可以观察他们的思维过程。 您将看到他们的手指如何滑过键盘。 您将看到他们如何努力应对算法。 您将学习新的开发人员工具和键盘快捷键。 您会沉浸在所有自己无法承担的无形事物中。

Being in the thick of the action is the ideal place to be.

处于最佳状态是理想的选择。

Take for example the Stradivarius violin. Stradivarius instruments have a reputation for excellent sound quality that (arguably) have no equal. Many theories have been presented to explain the superiority of Stradivarius, ranging from wood being salvaged from old cathedrals to special wood preservatives that were used back in the day. People have tried to reproduce it with poor results because we don’t know how Antonio Stradivari worked.

以Stradivarius小提琴为例。 斯特拉迪瓦里(Stradivarius)乐器因其出色的音质而享誉全球(可以说)无与伦比。 已经提出了许多理论来解释Stradivarius的优越性,从从古老的大教堂中抢救出来的木材到后来使用的特殊木材防腐剂,不一而足。 由于我们不知道安东尼奥·斯特拉迪瓦里(Antonio Stradivari)的工作原理,人们试图重现它的结果很差。

But imagine all the secrets and tricks that could be learned if you were in the same room as Antonio, sitting right next to him as he worked.

但是,想象一下,如果您和安东尼奥坐在同一个房间,坐在他旁边的时候,可以学到的所有秘密和窍门。

This is how you should treat your pair programming sessions. You should bring a healthy dose of curiosity as you watch your peer create Stradivarius-esque code. There’s no better opportunity to see all the blood, sweat, and tears that go into a line of code.

这就是对待配对编程会话的方式。 当您看着您的同伴创建Stradivarius式代码时,您应该充满健康的好奇心。 没有更好的机会看到所有流血,汗水和眼泪的代码。

For many, the opportunity to pair program is a rare luxury. But everyone can learn from others by looking at the code they’ve written.

对于许多人来说,配对课程的机会是一种难得的奢侈。 但是每个人都可以通过查看自己编写的代码来向他人学习。

Reading well-written code is like reading a well-written novel. It involves more interpretation on your part than if you were speaking directly with the author. But you can gather a wealth of information by reading through comments and code.

读写得好的代码就像读一部写得好的小说。 与您直接与作者交谈相比,它需要更多的解释。 但是您可以通过阅读注释和代码来收集大量信息。

For those skeptical about how much can be learned by reading someone else’s code, take note of this story. A high school student named Bill Gates went dumpster diving in a company’s trash to get their source code and learn their secrets.

对于那些怀疑通过阅读别人的代码可以学到多少东西的人,请注意这个故事。 一位名叫比尔·盖茨(Bill Gates)的高中学生在公司的垃圾箱里跳了垃圾箱,以获取源代码并了解其秘密。

If someone like Bill Gates went through all that trouble to read someone’s code, I think it’s worth it for us to open up a Github repo and do the same.

如果像比尔·盖茨这样的人在阅读某人的代码时遇到了所有麻烦,那么我认为打开Github存储库并执行相同操作是值得的。

Reading through code and learning from others is not a new concept. Tutorials are structured in a way that you follow a master through a coding journey. A well-written tutorial will feel like you’re sitting next to the writer. You get the opportunity to read about the problems they’re thinking about.

阅读代码并向他人学习并不是一个新概念。 教程的结构方式使您可以在编码过程中跟随大师。 精心编写的教程会让您感觉就像坐在作家旁边。 您有机会阅读他们正在考虑的问题。

Hypertext links provide resources for you to read through and even do so in the middle of the tutorial (you wouldn’t do that in a peer programming session). The comment section and social media outlets allow you to have conversations with the masters.

超文本链接为您提供了阅读资源,甚至在本教程的中间也提供了资源(您不会在对等编程会话中这样做)。 评论部分和社交媒体渠道使您可以与主持人进行对话。

I also watch people code on YouTube. I recommend the SuperCharged Live Coding Session series from the Google Chrome Developers’ YouTube Channel. You get to watch two Google engineers live-code a project. You get to see how they approach performance issues, struggle through typos like the rest of us, and get stuck.

我还在YouTube上观看人们的代码。 我建议Google Chrome开发者的YouTube频道提供SuperCharged Live Coding Session系列 。 您将看到两名Google工程师对项目进行实时编码。 您将看到他们如何处理性能问题,像我们其他人一样在错别字中挣扎,并陷入困境。

我从中学到的教训 (Lessons I learned along the way)

ESLint (ESLint)

Linting is a process of looking through your code for potential errors. It helps enforce code style and keeps your code consistent and clean. You can use your own custom style rules or use preset rules that follow conventional styles (such as one provided by Airbnb).

整理是查看代码中潜在错误的过程。 它有助于实施代码样式并保持代码的一致性和整洁性。 您可以使用自己的自定义样式规则,也可以使用遵循常规样式的预设规则(例如,Airbnb提供的样式)。

Linting is especially effective when working on a team of developers. It helps the code look like it was written by a single person. It also forces people to follow company style guides (that developers might not otherwise take the time to read).

在开发人员团队中工作时,整理尤其有效。 它可以使代码看起来像是由一个人编写的。 这也迫使人们遵循公司风格的指南(否则开发人员可能不会花时间阅读)。

Linters are for more than aesthetics. They force you to follow best practices. For example, they can tell you when to use the “const” keyword for variables that aren’t getting reassigned.

短绒不仅仅用于美学。 他们迫使您遵循最佳做法。 例如,他们可以告诉您何时对没有重新分配的变量使用“ const”关键字。

If you use React plugins, they can warn you about components that can be refactored into stateless functional components. They are also a great way of learning new ES6 syntax and even tell you where you can update your code with new features.

如果您使用React插件,它们会警告您有关可以重构为无状态功能组件的组件。 它们也是学习新ES6语法的好方法,甚至可以告诉您可以在何处使用新功能更新代码。

Here are instructions for quickly getting started with ESlint in your project:

以下是在项目中快速入门ESlint的说明:

  1. Install the ESlint package.

    安装ESlint软件包。
$ npm install --save-dev eslint

2. Configure the ESlint options.

2.配置ESlint选项。

./node_modules/.bin/eslint --init

3. Set up an npm script to run your linter in your package.json file (optional).

3.设置一个npm脚本以在package.json文件(可选)中运行您的linter。

"scripts": {  "lint": "./node_modules/.bin/eslint"}

4. Run the linter.

4.运行短绒。

$ npm run lint

Check out their documentation for more details on how to get started.

查阅他们的文档以获取有关如何入门的更多详细信息。

Many editors also have plugins that will lint your files as you type.

许多编辑器还具有可在您键入文件时将文件打毛的插件。

Sometimes linters might complain about code that you actually need, such as a console.log. You can tell your linter to ignore certain lines of code in their analysis.

有时候,短毛猫可能会抱怨您实际需要的代码,例如console.log。 您可以告诉linter在分析中忽略某些代码行。

To do this with ESlint, you can include the comments below:

为此,您可以在ESlint中添加以下注释:

// Single line Ignore console.log(‘Hello World’); // eslint-disable-line no-console
// Multiline Ignore /* eslint-disable no-console */ console.log(‘Hello World’); console.log(‘Goodbye World’); /* eslint-enable no-console */
检查缩小 (Check for minification)

I found a random “isCrushed()” function inside the source code that had no body to it. This was strange.

我在源代码中发现了一个没有正文的随机“ isCrushed()”函数。 真奇怪

But I found that its only purpose was to see if the code was minified. During minification, function names and variables are shortened. There was an if statement that checked if the “isCrushed()” function still existed with that name. A warning would be shown if the minified code was used in development.

但是我发现它的唯一目的是查看代码是否缩小。 在压缩期间,函数名称和变量会缩短。 有一个if语句检查该名称是否仍然存在“ isCrushed()”函数。 如果在开发过程中使用了缩小的代码,则会显示警告。

不要害怕错误 (Don’t be afraid of errors)

I had rarely used errors in my code outside of learning about it. JavaScript is a loosely-typed language so we should be paranoid about what gets passed into our functions. We should throw errors and scream like a strongly-typed language would.

除了了解它之外,我很少在代码中使用错误。 JavaScript是一种松散类型的语言,因此对于传递给函数的内容,我们应该抱有幻想。 我们应该像强类型的语言一样抛出错误和尖叫。

Finally use try…catch…finally statements with these errors. Doing so will make your code easier to debug and reason with in the future.

最后使用try ... catch ... finally语句,并显示这些错误。 这样做将使您的代码更易于调试和将来进行推理。

Take a look at that nice stack trace that errors produce in the console.

看一看在控制台中产生错误的堆栈跟踪。

Errors makes your intentions explicit. For example, if your “add()” function only expects numbers, then let the whole world know.

错误使您的意图明确。 例如,如果您的“ add()”函数只期望数字,那么请让全世界知道。

function add(a, b) {   if(typeof a !== ‘number’ || typeof b !== ‘number’) {     throw new Error(‘Invalid arguments passed. Expected numbers’);   }
return a + b; }
var sum = add(‘foo’, 2); // errors will prevent unintended consequences in your code
功能组成 (Function Composition)

There was a “compose()” function that built new functions out of existing ones:

有一个“ compose()”函数可以在现有函数的基础上构建新函数:

function compose(…funcs) {   if (funcs.length === 0) {     return arg => arg   }
if (funcs.length === 1) {     return funcs[0]   }
const last = funcs[funcs.length — 1]   const rest = funcs.slice(0, -1)   return (…args) => rest.reduceRight((composed, f) => f(composed),    last(…args)) }

If I have an existing function that squares a number and another function that doubles a number, I can combine them together into a new function.

如果我有一个将数字平方的现有函数和另一个将数字加倍的函数,则可以将它们组合成一个新函数。

function square(num) {   return num * num; }
function double(num) {   return num * 2;}
function squareThenDouble(num) {   return compose(double, square)(num);}
console.log(squareThenDouble(7)); // 98

I don’t know if I’ll ever use this, but it’s good to have this in my tools.

我不知道我是否会使用它,但是最好在我的工具中使用它。

本机方法 (Native Methods)

When I was looking at the “compose()” function, I ran into an Array method “reduceRight()” that I had never heard of. It made me wonder how many other native functions I haven’t learned.

当我查看“ compose()”函数时,遇到了一个我从未听说过的数组方法“ reduceRight()”。 这让我想知道我还没有学到多少其他本机函数。

Let’s look at a code snippet that uses the native Array method “filter()” and one that doesn’t, and see why it’s worth it to know what native functions exist.

让我们看一下使用本机Array方法“ filter()”和不使用本机Array方法的代码段,并了解为什么知道存在哪些本机函数是值得的。

function custom(array) {   let newArray = [];
for(var i = 0; i < array.length; i++) {     if(array[i]) {       newArray.push(array[i]);     }   }
return newArray; }
function native(array) {   return array.filter((current) => current); }
const myArray = [false, true, true, false, false]; console.log(custom(myArray)); console.log(native(myArray));

You can see how concise the code that uses “filter()” is. More importantly, we’re not reinventing the wheel. The “filter()” function has been used by millions of other users and is probably less buggy than your implementation.

您可以看到使用“ filter()”的代码多么简洁。 更重要的是,我们不会重新发明轮子。 “ filter()”函数已被数百万其他用户使用,并且可能比您的实现要少。

Before writing your own solution, check to see if the problem has already been solved in the language you’re using. You’ll be surprised how many utility methods a language can have. (For example, check out this Ruby method for repeated permutations in an array).

在编写自己的解决方案之前,请检查是否已使用您所使用的语言解决了问题。 您会惊讶于一种语言可以有多少种实用方法。 (例如,检查此Ruby 方法以获取数组中的重复排列)。

描述性功能名称 (Descriptive function names)

Looking through the source code, I saw a number of long function names.

查看源代码,我看到了许多长函数名。

  1. getUndefinedStateErrorMessage

    getUndefinedStateErrorMessage
  2. getUnexpectedStateShapeWarningMessage

    getUnexpectedStateShapeWarningMessage
  3. assertReducerSanity

    assertReducerSanity

Although they don’t roll off the tongue, there is no confusion about what they do.

尽管他们不会吐舌,但对他们的所作所为没有困惑。

Use descriptive names in your code. You will spend more time reading code than writing it, so make it easier for you and everyone else to read.

在代码中使用描述性名称。 与编写代码相比,您将花费更多的时间阅读代码,因此使您和其他所有人都更容易阅读。

The benefits of using long descriptive names far exceed the irritation you get from the extra keystrokes. Modern text editors have autocomplete features that help you type so you have no excuse to use “x” or “y” as variables.

使用长描述性名称的好处远远超过了从额外的击键操作中获得的刺激。 现代的文本编辑器具有自动完成功能,可帮助您键入内容,因此您没有借口使用“ x”或“ y”作为变量。

console.error与console.log (console.error vs. console.log)

Don’t use console.log for everything. If you have an error that you want to print out, use console.error. You get a nice red print out with a stack trace in your console.

不要为所有内容使用console.log。 如果您有要打印的错误,请使用console.error。 您会在控制台中获得带有堆栈跟踪的漂亮的红色打印。

Take a look at the documentation for the console and see what other methods are available. There is a built in timer (console.time()), you can print out your info in a table layout (console.table()) and much more.

查看控制台的文档 ,并查看其他可用方法。 有一个内置的计时器(console.time()),您可以按表布局(console.table())来打印信息。

Don’t be afraid to dig through Open Source code. You’ll definitely learn something and might even find something to contribute.

不要害怕深入研究开源代码。 您肯定会学到一些东西,甚至可能会找到一些可以贡献的东西。

Let me know what things you have learned by reading other people’s code.

让我知道您通过阅读别人的代码学到了什么。

翻译自: https://www.freecodecamp.org/news/what-i-learned-from-reading-the-redux-source-code-836793a48768/

redux代码

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值