Hi everyone ❤️

大家好❤️

For a while now I’ve been hearing my friends and colleagues complaining about how hard it was to get into Redux.

一段时间以来,我一直在听我的朋友和同事抱怨进入Redux有多困难。

I run a freeCodeCamp Study Group in the South of Portugal, Faro, so every week I try to motivate and mentor some fellow coders that have a lot of growing pains trying to make their way into programming.

我在葡萄牙南部的法鲁(Faro)运营着一个freeCodeCamp研究小组,所以每周我都会激励和指导一些编码人员,他们在尝试进入编程领域时会遇到很多麻烦 。

Dan Abramov created an amazing introduction course to Redux, which I had the pleasure to see in egghead.io, covering all the aspects of Redux. Also the Redux documentation site, here, is very complete.

Dan Abramov为Redux创建了一个很棒的入门课程,我很高兴在egghead.io中看到了该课程 ,涵盖了Redux的所有方面。 Redux文档站点( 此处 )也非常完整。

But for some reason many people still do not grok Redux.

但是由于某些原因,许多人仍然不喜欢Redux。

The point is that Redux has a considerable entry-level learning curve!

关键是Redux具有相当大的入门级学习曲线!

You have to understand a lot of abstractions, you have to do a more functional approach to programming in JavaScript, know a lot of ES6 features and also understand very well a lot of JavaScript concepts such as immutability.

您必须了解很多抽象概念,必须使用一种更具功能性的方法来进行JavaScript编程,必须了解许多ES6功能,并且还必须非常了解很多JavaScript概念,例如不变性。

So, that’s why it might be very difficult for those of you that started React a few months ago and are very enthusiastic to abstract your state into a Redux store.

因此,这就是为什么对于几个月前开始使用React并热衷于将您的状态抽象到Redux商店的人们来说,这可能是很难的。

You hear the chit-chat around the coffee machine of how Redux is acing it, about clean programming, single sources of truth and the three principles that drive this huge ‘tiny’ (2kB) library…

您会听到关于咖啡机Redux如何处理它的闲聊,有关干净编程,真理的单一来源以及驱动这个庞大的“小”(2kB)库的三个原则的信息。

So, no worries, you’ve came to the right place! This article is for you! And I’ll show you with an application first principle approach how easy it is to get the ball rolling with Redux.

因此,不用担心,您来对地方了! 本文适合您! 我将以应用程序优先的原则向您展示Redux使球滚动变得多么容易。

A lot of ink has already been spilled around this subject, but let’s go. Let me try to introduce you as fast as I can to Mr. Redux in a React context.

关于此主题,已经有很多墨水溅出来,但让我们开始吧。 让我尝试在React上下文中尽快向您介绍Redux先生。

To begin with this herculean task, I’m going to show you how to make a very simple counter application with the following user story:

首先要完成这项艰巨的任务,我将向您展示如何使用以下用户故事制作一个非常简单的计数器应用程序:

  1. display the current count number;显示当前计数数字;
  2. provide the user with two buttons, for incrementing and decrementing the count number.为用户提供两个按钮,用于增加和减少计数。

Okay, at this point you think: I could do that very quickly with local state.

好的,这时您会认为:我可以使用本地状态非常快地完成此操作。

True story! And that’s the way, mate! We’re going to start with a simple React example that uses local state and we’re going to transform the app into a React-Redux application.

真实的故事! 就是这样,伙计! 我们将从一个使用本地状态的简单React示例开始,并将该应用转换为React-Redux应用。

But, before that, let me introduce you the basic concepts and purposes of Redux in a quick intro.

但是,在此之前,让我快速向您介绍Redux的基本概念和目的。

01.基本概念 (01. Basic concepts)

Redux was created by Dan Abramov, and it’s defined as a “predictable state container for JavaScript apps.”

Redux是由Dan Abramov创建的,它被定义为“ JavaScript应用程序的可预测状态容器”。

The motivation for Dan to create Redux was that SPA complexity was increasing a lot. And we were left alone to manage the state of our data with two difficult concepts for the human mind to reason about: mutation and asynchronicity. He calls them “Mentos and Coke — Both can be great in separation, but together they create a mess”.

Dan创建Redux的动机是SPA的复杂性大大增加。 而且,我们不得不用两个难以理解的概念来管理我们的数据状态,这是人类头脑中不可思议的概念: 突变异步性 。 他称它们为“ Mentos和可乐 -两者的分离效果很好,但在一起却造成混乱”。

So Redux proposes to describe the whole state of your app as a plain object. To change something in state you need to dispatch actions. Actions are plain Javascript objects that describe what happened to your app.

因此,Redux建议将应用程序的整个状态描述为一个普通对象。 要更改状态,您需要调度动作。 操作是描述您的应用程序发生了什么的简单Javascript对象。

In the end, to tie actions and state together we write a function called a reducer. A reducer is just a Javascript function that takes state and action as arguments and returns the next state of the app.

最后,为了将动作和状态联系在一起,我们编写了一个称为reducer的函数。 reducer只是一个Javascript函数,它以状态和操作作为参数并返回应用程序的下一个状态。

Redux的三项原则: (Three Principles of Redux:)

  1. Single source of truth: the state of your whole app is stored in an object tree within a single store.

    单一事实来源:整个应用程序的状态存储在单个商店内的对象树中。

  2. State is read-only. This means that the only way to change the state is to emit an action (an object describing what happened).

    状态为只读。 这意味着更改状态的唯一方法是发出一个动作 (一个描述发生了什么的对象)。

  3. Changes are made with pure functions. Pure functions are functions that return a value only depending on the value of its arguments. They have no observably side-effects. When you call the same function with the same argument you always get the same return value. Pure functions also do not modify the arguments they receive. They actually return a new object, array, or function with the changes made to it.

    使用纯函数进行更改。 纯函数是仅根据其参数值返回值的函数。 它们没有明显的副作用。 当您使用相同的参数调用相同的函数时,您始终会获得相同的返回值。 纯函数也不会修改它们接收的参数。 他们实际上返回具有更改的新对象,数组或函数。

02.计数器应用程序(以本地状态进行响应,此处没有Redux) (02. The Counter App (React with local state, no Redux here))

Okay mates, getting back to where we were coming from, let’s make our small counter app with local state only.

好的伙伴们,回到我们的家乡,让我们让小型计数器应用程序仅具有本地状态。

To start these kind of boilerplates I always use create-react-app (CRA) with bootstrap (just to get things simple but a little bit more fancy).

为了开始这类样板,我总是使用带有引导程序的create-react-app(CRA)(只是为了使事情变得简单,但花哨的多一点)。

I kept the src/index.js which calls the <App /> component (playing the role of the main App view) and I’ve created a small stateful component called Counter.

我保留了src / index.js来调用<App />组件(扮演App主视图的角色),并且创建了一个名为Counter的小型有状态组件。

If you wanna play with the code you can clone it from my GitHub repo here (keep in mind that it’s on the branch LocalStateApp).

如果您想使用该代码,可以在这里从我的GitHub存储库中克隆它(请记住,它位于分支LocalStateApp上)。

So, let’s take a look at what we need to build our simple App.

因此,让我们看一下构建简单应用程序所需的内容。

As simple as it is out-of-the-box.

开箱即用就这么简单。

I start my App Component initialising the state with a count variable which by default is set to zero.

我使用一个count变量初始化状态来启动我的App Component,默认将其设置为零。

I’ve built a very simple render method which destructures the count from state and shows some text. It also invokes the Counter stateful component passing the count value into it, and calls a small method called renderButtons() to render the increment/decrement buttons.

我建立了一个非常简单的渲染方法,该方法从状态中解构计数并显示一些文本。 它还调用将有计数值传递到其中的Counter有状态组件,并调用一个名为renderButtons()的小方法来呈现递增/递减按钮。

Buttons call a method called updateCounter() and pass into it the type of update we want.

按钮调用一个名为updateCounter()的方法,并将所需的更新类型传递给该方法。

Here we are already building our way into Redux. One detail of actions in Redux is that, besides being simple objects that are up to you, they need to have a type property which is not undefined. (Just keep this in mind for now.)

在这里,我们已经在建立进入Redux的方式。 Redux中操作的一个细节是,除了是由您自己决定的简单对象外,它们还需要具有一个不确定的type属性。 (现在请记住这一点。)

So here we have our updateCounter method which is very similar to what a reducer is in Redux. It gets the current state of the app, it gets the action wanted, and in the end it returns the new state of your app.

因此,这里有updateCounter方法,该方法与Redux中的reducer非常相似。 它获取应用程序的当前状态,获取所需的操作,最后返回应用程序的新状态。

No magic at all! Redux is so natural and easy that you won’t feel the difference at all since you know two or three little details that make things seem very complex and hard to grok.

根本没有魔术! Redux非常自然和容易,您几乎不会感觉到差异,因为您知道两个或三个小细节,这些细节使事情看起来非常复杂且难以理解。

This is the final result of our app:

这是我们应用程序的最终结果:

03.计数器应用程序(带有Redux状态) (03. The Counter App (w/Redux State))

Okay friends! Let’s break down what we’ve done till now.

好的朋友! 让我们分解到现在为止的工作。

To install Redux you have to do:

要安装Redux,您必须执行以下操作:

npm install --save redux react-redux

npm install-保存redux react-redux

So after installing Redux your package.json dependencies should look like this ?.

因此,在安装Redux之后,您的package.json依赖项应如下所示?

Now what?

怎么办?

Let’s break our app! But not too much! ?

让我们打破我们的应用程序! 但是不要太多! ?

So my first step will be to remove the state from the App Component and create a Redux store on index.js:

因此,我的第一步是从应用程序组件中删除状态,并在index.js上创建Redux存储:

What have we done here? ☕️

我们在这里做了什么? ☕️

We’ve edited our main index.js file to create a Redux Store and pass it as a prop into our <App /> Component.

我们已经编辑了主要的index.js文件,以创建一个Redux商店,并将其作为道具传递到我们的<App />组件中。

You might notice the two imports on the top: Provider and createStore.

您可能会注意到顶部的两个导入:Provider和createStore。

You shall also notice the usage of the HOC <Provider> around <App/>. It works from the outside embracing our main app (it can also embrace Router stuff) in order to pass its API functions as props into our main App.

您还将注意到<App />周围的HOC <Provider>的用法。 它从外部拥抱我们的主应用程序(它也可以包含路由器的东西),以便将其API函数作为道具传递到我们的主应用程序中。

But wait!

可是等等!

What is the reducer in this variable definition?

这个变量定义中的reducer是什么?

Oh, we’re missing the reducer!

哦,我们缺少减速器!

So the store needs to receive at least one reducer function to actually know how changes to the state operate.

因此,商店需要接收至少一个reducer函数,才能真正知道状态更改的操作方式。

Let’s do it!

我们开始做吧!

In our old app we had that updateCounter method that we said was kind of a reducer.

在我们的旧应用中,我们有一个updateCounter方法,我们说它是一个简化器。

So let’s move it to index.js (you can also extract it to another file and import it but let’s keep things simple for now).

因此,让我们将其移至index.js(您也可以将其提取到另一个文件中并导入,但现在让我们保持简单)。

So we’ve extracted the updateCounter method from our App Component and we tweaked it a bit to give it some more context.

因此,我们从应用程序组件中提取了updateCounter方法,并对其进行了一些微调以提供更多上下文。

We’ve called it reducer. It’s the reducer we want to pass into the createStore method.

我们称之为减速器。 这是我们要传递给createStore方法的reducer。

We’ve also added state as an argument because when we’ve extracted it from the <App /> Component context, it is not aware of any state anymore. We also stopped using setState and started to return the new count according to the action type we’re receiving (destructured it from the action arg).

我们还添加了状态作为参数,因为当从<App /> Component上下文中提取状态时,它不再知道任何状态。 我们也停止使用setState并开始根据接收到的操作类型返回新计数(从操作arg对其进行了结构分解)。

We’ve used ES6 features to define an initialState by default if state is undefined. Remember what I told you above ?, that state couldn’t be undefined. It is one of Redux reducer’s conditions.

如果状态未定义,我们默认使用ES6功能来定义initialState。 还记得我在上面告诉您的内容吗,状态不能不确定。 这是Redux减速器的条件之一。

Besides that, nothing new everyone! Guess what? We have our reducer set and ready to do its job!

除此之外,没有什么新鲜的大家! 你猜怎么了? 我们已准备好减速机,并准备好工作了!

Now let’s pay attention to the actions!

现在让我们注意动作!

In our old app they were the updateCounter invocation. But now as you remember we need to use the dispatch() method from Redux to dispatch actions so we need to add this layer of the API to our app.

在我们的旧应用中,它们是updateCounter调用。 但是现在您还记得,我们需要使用Redux中的dispatch()方法来分派操作,因此我们需要将API的这一层添加到我们的应用程序中。

We’ve tweaked only two things folks! We’ve got the dispatch method, destructuring it from the props. Remember the <Provider /> HOC? Its role is to introduce these few Redux methods into your main app.

我们只调整了两件事! 我们已经有了调度方法,可以从道具中将其破坏。 还记得<Provider /> HOC吗? 它的作用是将这几种Redux方法引入您的主应用程序。

Instead of calling this.updateCounter we are now calling an updateCounter detached function supplying to it the action type (as we already were in the old app).

现在,我们不再调用this.updateCounter,而是调用一个updateCounter分离函数,向其提供操作类型(就像我们在旧应用程序中一样)。

Let’s now see what’s the new updateCounter function:

现在,让我们看看新的updateCounter函数是什么:

Okay, nothing new, we just receive the dispatch method and return it with the type of action we want to fire.

好的,没什么新鲜的,我们只接收dispatch方法,并以我们要触发的操作类型返回它。

At this time we’ve already created the store. We’ve created the reducer to grab the previous state of the app and the action and return the new state. We’ve built an action function to dispatch our app actions.

目前,我们已经创建了商店。 我们已经创建了reducer来获取应用程序和操作的先前状态并返回新状态。 我们已经构建了一个动作函数来调度我们的应用动作。

What more? This should be working by now! Why it is not?

还有什么? 现在应该可以工作了! 为什么不是呢?

Ohhh! Our App Component must be connected to Redux!

哦! 我们的应用程序组件必须连接到Redux!

So this is our final step everyone! ?

因此,这是我们所有人的最后一步! ?

We start by importing the connect method from react-redux (into our App.js file).

我们首先从react-redux导入connect方法(到我们的App.js文件中)。

Now at the end of our file, where we do the export default app of our component, we need to do the connection:

现在,在文件末尾,我们在其中执行组件的导出默认应用程序,我们需要进行连接:

Okay! Remember we’ve removed the local state from our App component?

好的! 还记得我们已经从我们的App组件中删除了本地状态吗?

So… how do we inject the state of the store into our component?

那么……我们如何将商店的状态注入到我们的组件中?

We need to do a “mapStateToProps”! Get used to this because it will always be needed. App component will receive the new state as a prop. You have no this.state anymore!!

我们需要做一个“ mapStateToProps”! 习惯这一点,因为将始终需要它。 应用组件将接收新状态作为道具。 您没有this.state了!

mapStateToProps grabs the state from the connect method (HOC) and binds it to App Component.

mapStateToProps从connect方法(HOC)中获取状态并将其绑定到App Component。

And that’s it everyone! By this time your app should be running.

就是每个人! 到此时,您的应用程序应已运行。

Feel free to take a look at the code in my GitHub repo (branch ReduxStateApp) here.

请在此处随意查看我的GitHub存储库(分支ReduxStateApp)中的代码。

Of course there’s a lot of things to learn after this, but this is the main first step for you to understand how to get the ball rolling with Redux.

当然,此后还有很多事情要学习,但这是您了解如何使Redux发挥作用的主要第一步。

Now I ask you to do the homework: check out the two apps! Make sure you grok all the steps and compare them. Put a lot of console.log to understand what’s going on, and above all accept that there’s an API in Redux that has a few but strict rules. Not everything is so logical for an entry-level as it’s expected to be! But those are only good growing pains for the sake of JavaScript!

现在,我要求您做作业:检查这两个应用程序! 确保您完成所有步骤并进行比较。 放很多console.log来了解发生了什么,最重要的是,Redux中有一个API,它有一些但严格的规则。 对于入门级而言,并非所有事情都像预期的那样合理! 但是,仅出于JavaScript的考虑,这些只是长大的痛苦!

Always remember to Be Strong and Code On everyone ❤️

永远记住要坚强并为每个人编码❤️

And keep your pain in check with a good and hot ☕️ ️

并通过好又热的☕️️来控制疼痛

04.参考书目 (04. Bibliography)

01. Redux Docs

01. Redux文档

02. egghead.io Dan Abramov’s course on Getting Started With Redux

02. egghead.io Dan Abramov的Redux入门课程

翻译自: https://www.freecodecamp.org/news/redux-get-the-ball-rolling-in-10min-9d9551ff4b3c/

如何在10分钟内让Redux发挥作用相关推荐

  1. github创建静态页面_如何在10分钟内使用GitHub Pages创建免费的静态站点

    github创建静态页面 Static sites have become all the rage, and with good reason – they are blazingly fast a ...

  2. 以太坊区块链同步_以太坊69:如何在10分钟内建立完全同步的区块链节点

    以太坊区块链同步 by Lukas Lukac 卢卡斯·卢卡奇(Lukas Lukac) Ethereu M 69:如何在10分钟内建立完全同步的区块链节点 (Ethereum 69: how to ...

  3. es6 ... 添加属性_如何在10分钟内免费将HTTPS添加到您的网站,以及为什么您现在不止需要这样做......

    es6 ... 添加属性 by Ayo Isaiah 通过Ayo Isaiah 如何在10分钟内免费将HTTPS添加到您的网站,以及为什么现在比以往更需要这样做 (How to add HTTPS t ...

  4. javascript创建类_如何在10分钟内使用JavaScript创建费用管理器

    javascript创建类 by Per Harald Borgen 通过Per Harald Borgen 如何在10分钟内使用JavaScript创建费用管理器 (How to create an ...

  5. bootstrap设计登录页面_前端小白如何在10分钟内打造一个爆款Web响应式登录界面?...

    对于前端小白(例如:专注后端代码N年的攻城狮),自己编写一个漂亮的Web登录页面似乎在设计上有些捉襟见肘,不懂UI设计,颜色搭配极度的混乱(主色,辅助色,配色,色彩渐变,动画效果等等,看起来一堆乱七八 ...

  6. 如何在10分钟内开始使用MongoDB

    by Navindu Jayatilake 通过纳文杜·贾亚提莱克 如何在10分钟内开始使用MongoDB (How to get started with MongoDB in 10 minutes ...

  7. 如何在10分钟内构建交互式HTML5广告

    本文出生地传送门→→→→→如何在10分钟内构建交互式HTML5广告---静华网-一个有气质的网站 随着Flash的消亡,交互式广告的责任被传递给了HTML5.在这里,我们将学习如何在短短10分钟内建立 ...

  8. 【手把手】如何在10分钟内搭建一个以太坊私有链?

    在开发以太坊时,很多时候需要搭建一条以太坊私有链,这篇来自作者熊丽兵的文章,手把手教你10分钟内如何在Mac上进行搭建. 作者 | 熊丽兵 整理 | 科科 阅读本文前,你应该对以太坊语言有所了解,如果 ...

  9. 零Python编程基础,如何在10分钟内合并1000个Excel表格?

    对于大部分的文秘,财务人员,管理人员,都会面临大量的Excel表格整理工作,当Excel表格超过100,甚至有1000个时,对于他们来说,无疑是个噩梦. 下面的场景,您是否熟悉: 接收不同部门的大量E ...

最新文章

  1. R语言使用fmsb包、gradar包可视化雷达图(radar chart、蜘蛛图spider plot)、ggpubr包可视化点图、GGally包可视化多变量的平行坐标轴图
  2. Spring Boot中验证码实现kaptcha
  3. Struts2-EL表达式为什么能获取值栈数据
  4. Python中is和==的区别
  5. (轉貼) ThinkPad鍵盤設計原理和哲學 (NB) (ThinkPad)
  6. Leecode31. 下一个排列——Leecode大厂热题100道系列
  7. Git初学札记(七)————合并分支(merge)
  8. centos7 删除zabbix_Zabbix服务器端运行中显示为“不”的解决方式
  9. UVA11991 Easy Problem from Rujia Liu?题解
  10. VS 2010 复制代码到word出现乱码解决办法
  11. Unity 连接MySql数据库
  12. php 卡密支付破解 yj,卡密功能自助授权功能源码
  13. 【正点原子STM32连载】第一章 本书学习方法 摘自【正点原子】MiniPro STM32H750 开发指南_V1.1
  14. Linux 串口驱动与使用
  15. Vue JSON校验格式化编辑框 -- jsoneditor
  16. matlab语言在天线设计,matlab语言在天线设计中的运用
  17. 天蓝色房间(密室逃脱三)攻略
  18. STM32学习笔记——通用定时器的PWM介绍及配置
  19. 【总结】1183- 毕业去字节之前的一些感想
  20. 通行时间可调的两路口交通灯设计实验(基于Multisim仿真)

热门文章

  1. 从外包月薪5K到阿里月薪15K,原理+实战+视频+源码
  2. C# 利用DotRas 操作adsl
  3. 2019.04.09 电商25 结算功能1
  4. BFS(广度优先搜索)
  5. 从汇编去分析线程安全
  6. iOS 多参数 ...NS_REQUIRES_NIL_TERMINATION 的写法
  7. 十进制数转化为2进制后有多少个1
  8. Spring支持如下5种作用域
  9. P2P原理及UDP穿透简单说明
  10. Google 地图 API 参考