【中英字幕】理解 React、Redux 和 React-Redux - Understanding React, Redux, and React-Redux

React is indeed a trending JavaScript library for building great UI components. But I am here to talk about something which I believe is very important and somehow every application (be it a React or any other platform specific) needs it.

React确实是一个用于构建出色UI组件的热门JavaScript库。但我在这里想谈论的是我认为非常重要的一点,也是每个应用程序(无论是React还是其他特定平台)都需要的东西。

What is it? The answer is State Management. I don’t want to miss out on anything, so let me first answer what does state management means when it comes to application development.

是什么呢?答案是状态管理。我不想漏掉任何细节,所以让我首先回答在应用程序开发中状态管理意味着什么。

State Management is some thing which takes care of the changes in any part of the components/application. In layman term, it is nothing but a management of a data state for event handling inside the application.

状态管理是一种负责处理组件/应用程序任何部分的变化的机制。通俗地说,它无非是对应用程序内部事件处理的数据状态的管理。

既然我们已经了解了这个强大的平台React,让我们来理解一下Redux是什么。

Now, since we have already known this great platform React, let us understand what Redux is.

Redux是JavaScript应用程序中的可预测状态容器。这意味着什么呢?嗯,Redux通过将整个应用程序中需要更改的所有状态存储在一个地方来帮助进行状态管理,我们通常称之为“Store”。

Redux is a predictable state container in Javascript app. What does that mean? Well, Redux helps in state management by storing all the states which needs to be changed through out the app in one place, which we usually call it as Store.

需要一个例子!好的,这里有一个[非常基础的]:假设我们正在使用一个应用程序,其中包含用户数据的导航抽屉。现在当您转到个人资料页面并更改用户数据时,当您返回导航抽屉时,数据会自动更改,而无需任何问题!这不是很神奇吗?这仅仅是因为状态管理,而在React中,著名的状态管理库就是Redux。

You need an example! Well, here you go [very basic]: Let’s say we are using an application, having a navigation drawer containing User’s Data. Now when you go to the profile page, and make some changes in your data which is User’s data only, and when you come back to the navigation drawer, it changes the data automatically without even problem! Isn’t it amazing. This is because of State Management only, and in React, the famous State Management library is Redux only.

缺点:Redux带有大量样板代码,相信我,许多JavaScript开发者并不是这个库的铁杆粉丝。如果您不正确地使用它,有可能导致应用程序崩溃或表现不当。因此,在使用之前请三思。现在,我不想让这篇博客变得太长,但请查看这个链接,里面有一个"Why you don’t wanna use Redux?"的内容。你可能觉得很有趣,但讽刺的是,Redux的开发者写了这篇文章! :D

Disadvantages: Redux comes with a lot of boilerplate, and believe me many JS developers are not a big fan of this library. And if you don’t follow it properly, chances are, your application might break or behave inappropriately. So think before you use. Now, I don’t want to make this blog long enough, but check this link out, which has Why you don’t wanna use Redux? You might find it funny, but the irony is, the one who developed Redux wrote this article! :D

现在,既然你已经做出了继续前进并尝试处理这个问题的选择,我在这里将通过一些类比而不是代码来帮助你理解。[代码] 你随时随地都可以在互联网上找到。

Now, since you have made your choice to move further and try to deal with this, I am here to help you understand with some analogies, and not code. [Code] That you will get it on the internet any time, any where.

首先,让我们回答这个问题,为什么我们真的想要首先使用React-Redux。

First of all let us answer this question, why we really wan to use React-Redux in the first place

React-Redux,正如其名称和官方文档所述,将React应用程序与Redux绑定在一起。仍然感到困惑吗?让我为你解释一下,因此React-Redux允许你在React应用程序中使用Redux的所有操作。

React-Redux as the name and the official documentation says, it binds the React application for the Redux. Still confusing? Let me break it down for you, so React-Redux lets you use all the operations from Redux in the React application.

现在是最令人畏惧的部分,理解这些样板代码是什么。但在此之前,我们可能有一些需要解决的问题。以下是这些问题:

Here comes the most dreadful part, and understanding what this boilerplates are. But before that we might have some question which needs to be resolved. And here it goes:

Q1. 如果Redux可以在普通的JavaScript应用程序中使用,为什么要使用React-Redux? 答案:的确,Redux可以在JavaScript应用程序中使用,但当涉及到使用React-Native时,我们需要一些东西,使我们的组件能够使用Redux,而这些东西就是mapStateToProps和mapDispatchToProps。而使上述操作生效的是connect()。Provider(只由React-Redux提供)在进行状态更改时是最重要的要使用的东西,它能够确保你的业务逻辑与应用程序逻辑在状态管理操作上安全地分开。现在还有其他与React-Redux相关的事物,但我假设你会在官方文档中找到它们。

Q1. If Redux can be used in normal JS application, then why to use React-Redux? Answer: Redux is indeed usable in JS application, but when it comes to using React-Native, we require somethings which can make our component capable of using Redux, and these are mapStateToProps and mapDispatchToProps. And which makes the aforementioned think work is connect(). Provider (which is provided by React-Redux only) is the most important thing to be used when it comes to making all things work on your state change throughout your app, which is keeping your business logic separate from the application logic for state management operation safely. Now there are other things which are associated to React-Redux, but I assume, you would find in the official documentation.

 

Q2. 如果React-Redux已经引入了Hooks,为什么还要使用上述的connect(),mapStateToProps和mapDispatchToProps? 答案:React-Redux最近引入了Hooks,大约一年前。现在,使用不同的Hooks会涉及到一些边缘情况,它们替代了Redux实现中的所有三个要素。其中一些情况包括:

  1. 处理具有嵌套数据的Store对象。例如,用户可能具有复杂的数据结构,当你尝试通过对象表示法在状态管理中进行更改时,你的应用程序可能会出现问题。
  2. 感兴趣了解更多吗?这里是官方链接供你参考。Hooks | React Redux

Q2. If Hooks have already been introduced in React-Redux, then why use the above connect(), mapStateToProps and mapDispatchToProps? Answer: React-Redux has introduced the hooks recently, like an year. Now, there are edge cases which are associated to using different hooks which. replaces all the three assets to Redux implementation. Some of them are: Dealing with Store Objects which have nested data. For example: User can have complicated data structure, and when you will try to deal with making changes in your state management through object notation, your application might break. Interested in reading more? Here is the official link for you.

Phew! 感到累了吗?休息一下,继续阅读这篇博客,因为即将揭示精华内容。我们将讨论:

  1. 在React-Redux中使用的样板的类比
  2. 使用样板的正确方法

我相信你可能已经被上述指引吸引住了。所以让我们逐一深入主要内容。首先,让我们回答一个问题,我们如何以简单/通俗的方式理解这些样板。我有一些东西要给你,通过它我也理解了这些样板。让我们看看那是什么。

Phew! Feeling tired? Take a quick break and continue reading this blog, cos the cream data is about to come. We are going to be talking about: Analogies on the boilerplates used in the React-Redux What is the right approach for using the boilerplates I am sure you might have got intrigued by the above pointers. So let us start diving into the main content one by one. So, let us first answer the question, how do we understand the boilerplates in a simple/layman way. I have something for you, with which I also understood these boilerplates. Let us see what it that.

上面的图片描述了在状态管理过程中涉及的步骤。从技术上讲,这就是Redux的内容。现在,上面显示在蓝色框中的东西就是你的样板代码。我知道,你可能会想,是不是必须要做这些事情来使用Redux?答案是肯定的,这也是为什么不是每个开发者都期待使用Redux的原因。

The above picture depicts what is the process which is involved during the state management process. Technically speaking, this is what Redux is about. Now, the above things which is shown in the blue box are your boilerplates. I know, you will think, are these things needs to be done for playing around with the Redux? The answer is yes, and that is why not every developer looks forward to use Redux.

但别担心,我将给你一些类比,帮助你理解如何以更简单的方式处理它。而最好的方法确实是理解。

But don’t worry, I will give you some analogies which will help you understand how to tackle it in a simpler way. And the best way is indeed understanding.

View(视图):它只是应用程序的前端,无论发生什么变化,都应该在应用程序上反映出来。现在,在类比中,我会说这是你从前面看到的商店。我们称之为玩具商店。你站在前面看着它,如果有人购物,或者如果商店得到更多的玩具,你会看到商店发生的变化。这就是视图,我们将在后面使用它来理解其他样板代码。

View: It is nothing but the front-end of the application, what ever changes happens, it should reflect the same on the application. Now, in an analogy I would say a store which you see from the front. Let us call it as a toy store. You are standing in front of it and looking at it, if somebody purchase, or if the store gets some more toys, you see the changes being done in the shop. This is a View, and we will use it further to understand the other boilerplates.

Store(存储):如果我们谈论这个,名称揭示了一切。存储基本上将所有的状态管理数据保存在一个地方,因此为了类比理解,我们在视图中谈到的玩具商店将所有的玩具都保存在它的店里。一些其他商店则保存其他物品。因此称为“存储”。

Store: If we talk about this, the name depicts every thing. Store basically keeps all your state management data in one place, so to understand in an analogy, a toy store which we talked about in the View keeps all the toys in it’s store. Some other store keeps other stuffs. Hence stores.

Action(操作):在Redux术语中,必须向Reducer分发一个操作,以便根据发送的操作进行状态管理,最终将在我们应用程序的视图中反映出来。现在,我们已经看到了两个新事物,我们需要理解它们,这就是:操作和分发。我们如何理解它们,它们之间又是如何联系的呢?好吧,将操作看作是进入你脑海的一个想法,例如,当你进入玩具店时,你想购买一个或多个玩具。而分发是从你嘴里发出的,基本上是你的声音/命令/请求,它向店主发送了一条消息,说明你为什么来到店里。

Action: In Redux term, it has to dispatch an action to the Reducer, so that the state management can be done according to the action sent, which will eventually be reflected in the View of our application. Now, we have seen two new things, which we need to understand, and these are: Action and Dispatch. How can we understand both of them, and how are they linked with each other? Well, take Action as a thought which comes into your mind, when you enter inside the toy shop, for example, I want to buy a toy or many toys. And Dispatch is something which comes out of your mouth, basically your voice/command/request, which sends a message to the Shopkeeper on why have you come to the shop.

Reducer(减速器):在Redux语言中,Reducer是一种对存储中的State对象进行更改的机制,以便在视图中反映出来。复杂,对吧?现在让我们以类比的方式理解它,现在你已经进入商店,并提出(分发)购买玩具的请求(操作)。你向站在商店另一侧的一个人提出请求,我们称之为店主,但他/她也是一个Reducer。你的下一个问题可能是如何?那么让我告诉你,一旦你提出请求,店主会为你拿起所需的物品,并用货币交换给你。现在我们先忽略货币的部分,集中在玩具的减少上。那么在这个过程中实际上发生了什么呢?店主(Reducer)通过减少店内的玩具数量对店进行了更改,因此视图(玩具商店)也发生了变化,即商店中的玩具数量现在已经改变了。

Reducer: In Redux language, it is something which makes changes to the the State object in the Store, to be reflected in the View. Sophisticated, right? Now let us understand it in the analogical way, now you have entered into the store, and asked (Dispatched) for buying a toy (Action). The request you have raised to a person who would be standing on the other side of the store, we call him/her a shopkeeper, but he/she also is a Reducer. Your next question would be how? Then let me tell you how, as soon as you raise a request, the shopkeeper picks up the desired item for you and gives it to you in exchange of money. Now let us neglect the money part for a while, and focus on the toy reduction. So what happened actually in between the process? The shopkeeper (Reducer), made changes in the store by reducing the number of toy from the store, and hence the View (Toy Shop) is also changed, that is, the number of toys in the shop is changed now.

然后你开心地回到家,甚至没有意识到你实际上在现实生活中执行了Redux状态管理。:D 这不是很神奇吗?我相信,你现在可能已经真正理解了这些样板的实质。如果还没有,请再次阅读,或者同时观看一些视频,或文档。无论哪个来源都会让你更好地理解我在博客中写的东西。

You then go to your home happily, without even realizing that you have actually performed a Redux State Management in real life. :D Isn’t it amazing. I believe, you might have got the real essence of the boilerplates by now. If not, read it once again, or watch some videos simultaneously, or docs. Whatever source which will make you better understand the things which I have written in the blog.

谈到回答下一个重要问题,即如何在我们的应用程序中使用Redux的样板,以下是一些建议:

Coming to answering the next major question, and that is, how to approach the boilerplates or Redux in our application

免责声明:开发者有他们自己的编码方式,为Redux结构化文件也有各自的方式。我将要告诉你的是我在React应用程序中处理Redux的适合方式,随时随地都可以按照最适合你情况的方式来做。

Disclaimer: Developers have their own way of coding, structuring the files for Redux. Whatever I am going to tell is my suitable way of doing the Redux in the React application, feel free to follow your way of doing things which is best for your case.

正确的处理React-Redux实现的方式是:

  1. 创建Actions和Action Creators: 现在你可能对Action Creators感到困惑。请允许我解释一下,Action Creators只是使你的动作安全定义的额外一步,这样当你的代码增长时,你总是可以回到你的创建者并进行更改。处理错误变得更加容易和安全。Action Creators接受来自Actions文件的动作类型。 ==> 现在,动作类型是一组常量,你应该始终维护一个单独的文件来定义所有常量,并在需要的地方使用它。这样,动作类型文件的单一更改将在每个文件中进行更改。无需在每个文件夹中显式执行它。例如:const BUY_TOY = "BUY_TOY"。现在使用常量BUY_CAKE,它将在任何地方都是一致的。让我们看看你的动作创建者是什么样子的:

The right way of approaching your React-Redux implementations are: Create your Actions and Action Creators: Now you might be feeling confused on what Action Creators are. Allow me to explain, Action creators are nothing but an extra step of making your actions defined safely, so that when your code grows, you can always come back to your creator, and make changes. Handling bugs becomes easy and safe. Action Creators, accept the action type which comes from the Actions file. ==> Now Action types, are set of constants and you should always maintain a separate file in order to define all your constants, and use it places wherever required. In this way, a single change in the Action types’ file, will make changes in every file. No need to explicitly doing it in every folder. Example: const BUY_TOY = “BUY_TOY”. Now use the constant BUY_CAKE, and it will be coherent every where. Let us see how you action creator looks like:

请注意,BUY_TOY 是来自另一个文件 ./actionTypes,在该文件中我们根据上述示例以粗体字定义了 BUY_TOY 常量。

Note that BUY_TOY is coming from another file ./actionTypes where we have defined the BUY_TOY constant as per the above stated example in bold.

创建你的Reducer:对于reducers,它接受两个参数,一个是State,必须在函数中初始化,另一个是Action。同样,action类型将来自 ./actionTypes。所以你看到你的代码结构是多么重要。Reducer的作用基本上是根据你的动作对状态执行操作,最终只会在视图中进行更改。此外,你的状态应该以对象形式包含所有数据。让我们看一下我们的reducer是什么样子的:

Create your Reducer: For reducers, it accepts two arguments, one is State, which has to be initialized in the function, and another is Action. Again, the action type will come from the ./actionTypes. So you see how important is structuring of your code. What reducer does is, basically based upon your action performs the action on the States, which eventually make changes in the View only. Also, your state should consist of all the data in object form. Let us take a look, how our reducer looks like

与Reducers相关的还有一些其他事情,其中最重要的是它是不可变的。什么是不可变性?不可变性意味着你不能直接更改reducer,为了使事情成为可能,我们首先创建/复制我们的状态,然后进行更改。虽然你可以通过某些方法进行可变更改,但我认为我将分享的链接会告诉你更多。此外,有一个库我想谈谈,它能高效地处理你的Reducers,那就是ImmerJS:这是一个美丽且屡获殊荣的库,它处理Reducers以及不可变性。这是链接给你。ImmerJS

There are certain other things, which are related to Reducers, one of them and the most important of all is, it is immutable in nature. What is Immutable? Immutable means, you can alter the reducer, and to make things possible, we first create/make a copy of our state, and then make changes. Although, there are things present at your disposal of doing the mutable changes for the reducer, but I believe the link which I will share will tell you more about it. Although, there is one library which I want to talk about which handles your Reducers efficiently, that is, ImmerJS: A beautiful and award winning library that handles the reducers, along with the immutability. Here is the link for you.

创建存储:既然您已经成功创建了您的 Reducer,现在是将它们全部绑定在一个称为存储的地方的时候了。我们将如何做到这一点,这里有一个例子。

  • Creating a Store: Now that you have successfully created your Reducers, it is time to bind all of them in a place, called as store. How will we do that, here is the example.

最后一步 => 提供存储以便整个应用程序使用:现在我们有了存储,需要将其提供给您的应用程序,以便应用程序随时随地都能访问存储项的更新。我们应该如何做到这一点?只需转到您的App.js或index.js文件,并将您的项目绑定在React-Redux的Provider组件内,该组件接受一个名为store的prop,该prop必须由我们上面创建的use来提供。让我们看看如何做:

Final Step => Providing the store to be available for your whole application: Now that we have the store, the same has to be provided to your application, so that the application can access the store item’s update any time anywhere. How can we do that, just go to your file in App.js or index.js and bind your project inside the Provider, which is a component of React-Redux, accepts a prop as store, which has to be provided by use, which we created above. Let us see, how it is done:

太棒了!你刚刚很好地处理了这些样板。现在还有一件事情剩下,为了处理状态更改,当你在视图中并且想要进行更改时,它应该反映出来。这部分我将留给你,这样你可以阅读并实施。如果你理解了上面的内容,处理状态管理对你来说将不会那么困难。让我给你一些建议,你必须阅读关于mapStateToPropsmapDispatchToPropsconnect的内容。还有一些React-Redux的钩子,比如useSelectoruseDispatch

这只是一个关于如何在React应用程序中使用Redux和React-Redux开始状态管理的非常基础的例子。还有更多的东西等着你,但除非你很好地理解了如何很好地实现基本的东西,否则不要立即开始。这里有一些链接,可以让你更深入地了解Redux和React-Redux。一定要阅读文档,这将在未来对你有所帮助。

And voila! You have just handled the boilerplates nicely. Now one more thing which is remaining in order to handle the state change, and that is when you are inside the view and you want to make changes, so that it should reflect. That I will leave it to you, so that you can read, and implement. If you have understood the above content, handling the state management would be not so difficult for you. Let me give you some hints, you must read about mapStateToProp, mapDispatchToProp, and connect. React-Redux hooks like useSelector and useDispatch. This was a very basic example on how to get started with State management in React application using Redux, React-Redux. There are more things for you, but do not start off with that immediately unless you have a better understanding of how to do the basic implementation nicely. Here are the links for you to get more insights on the Redux, React-Redux. Do read the docs, it will help you in the long run.

文档:

Getting Started with Redux | Redux

Why Use React Redux? | React Redux

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值