redux logic_Redux-Logic简介
redux logic
by Sam Ollason
通过萨姆·奥拉森(Sam Ollason)
Redux-Logic简介 (An Introduction to Redux-Logic)
This article will go through a high-level overview of Redux-Logic. We will look at what is it, why it is needed, how it differs from other Redux middleware and why I think it’s the best choice. We will then see an example of a simple Weather app to demonstrate how the core concepts are put into practice.
本文将对Redux-Logic进行高层概述。 我们将研究它的含义,为什么需要它,它与其他Redux中间件有何不同以及为什么我认为它是最佳选择。 然后,我们将看到一个简单的Weather应用程序的示例,以演示如何将核心概念付诸实践。
This article assumes you have a good understanding of React and Redux.
本文假设您对React和Redux有很好的了解。
Redux快速复习 (A quick refresher on Redux)
Redux is a state container for JavaScript applications and is commonly used with React. It provides a central place for storing data that is used across your application. Redux also provides a framework for making predictable state mutations. Using Redux makes it easier to write, understand, debug and scale data-driven and dynamic applications.
Redux是JavaScript应用程序的状态容器,通常与React一起使用。 它提供了一个中心位置来存储在整个应用程序中使用的数据。 Redux还提供了进行可预测状态突变的框架。 使用Redux使编写,理解,调试和扩展数据驱动的动态应用程序变得容易。
In Redux, components call action creators which dispatch actions. Actions are (usually!) small plain objects that express an intent or an instruction. The actions can also contain ‘payloads’ (i.e. data).
在Redux中,组件调用分派action的 动作创建者 。 动作(通常是!)是表示意图或指令的小型普通对象。 这些动作还可以包含“有效载荷”(即数据)。
Application state is managed by reducers. They sound more complicated than they are! Actions are handled by a root reducer which then passes the action and the payload to a particular reducer. This reducer will take a copy of the application state, mutate the copy (according to the action and its payload) and then update the state in the application Store.
应用程序状态由reducers管理。 他们听起来比他们还复杂! 动作由根减速器处理,然后将动作和有效负载传递给特定的减速器。 这种减速将采取应用状态的副本 , 变异 副本 (根据行动和它的有效载荷),然后更新应用程序商店中的状态。
为什么需要Redux Logic? (Why the need for Redux Logic?)
By default, all actions in Redux are dispatched synchronously. This presents a challenge for any application that needs to support asynchronous behaviour such as fetching data from an API … so pretty much any application!
默认情况下,Redux中的所有操作都是同步分派的。 对于需要支持异步行为(例如从API提取数据)的任何应用程序来说,这都是一个挑战……几乎所有应用程序都如此!
To handle async behaviour using Redux, we need some kind of middleware that does some processing between when the action is dispatched and when the action reaches the reducers. There are several popular libraries for providing this functionality.
为了使用Redux处理异步行为,我们需要某种中间件 ,该中间件在分派动作和动作到达化简之间进行一些处理。 有几种流行的库可提供此功能。
After exploring the various options, I have been using Redux-Logic in a variety of projects for a while now and have found it to be great!
在探索了各种选项之后,我已经在各种项目中使用Redux-Logic已有一段时间了,并且发现它很棒!
Redux-Logic生命周期 (Redux-Logic lifecycle)
Redux-Logic provides middleware that performs some processing between when an action is dispatched from a component and when the action reaches a reducer.
Redux-Logic提供了中间件,该中间件在从组件分派动作到动作到达化简器之间执行一些处理。
We use the redux-logic library to create ‘Logic’. These are essentially functions that intercept particular plain object actions, perform asynchronous processing and then dispatch another plain object action. Logic functions are really declarative and flexible, as we shall see!
我们使用redux-logic库创建“逻辑”。 这些本质上是拦截特定普通对象操作,执行异步处理然后分派另一个普通 对象操作的函数。 逻辑功能实际上是声明性和灵活的,正如我们将要看到的!
An important thing to take away here is that all actions that Redux-Logic works with are plain objects. The action that is dispatched by the UI component and the action that is then dispatched by the Logic will always be a plain object (as opposed to, for example, a function). We will revisit this below when we compare different middleware options.
这里要注意的一件重要事情是,Redux-Logic进行的所有操作都是纯对象 。 UI组件分派的动作和Logic以后分派的动作将始终是普通对象(例如,与函数相反)。 当我们比较不同的中间件选项时,我们将在下面重新讨论。
Under the hood, Redux-Logic uses ‘observables’ and reactive programming. Read more about that here.
在后台,Redux-Logic使用“可观察对象”和React式编程。 在这里有关它的信息 。
数据流 (Data flow)
Below, for comparison, is a diagram I created showing the important points in the lifecycle of a synchronous redux process. There is no middleware included (because none is needed!).
作为比较,下面是我创建的图表,显示了同步redux流程生命周期中的重要点。 不包含中间件(因为不需要中间件!)。
Now here is a diagram showing the important parts of a project that use the redux-logic library to handle asynchronous actions. This will be useful to refer to later alongside the example below.
现在,这里的图显示了使用redux-logic库处理异步操作的项目重要部分。 这对于以后在下面的示例中进行参考将很有用。
You can see how the middleware operates in between when an action is dispatched and when it is handled by a reducer.
您可以看到中间件在调度动作和由化简器处理之间的运行情况。
与其他解决方案的主要区别 (Main differences from other solutions)
Redux-Thunk is a popular choice for Redux middleware that also allows you to support asynchronous behaviour. To handle asynchronous behaviour using Redux-Thunk your actions creators have to return functions as opposed to returning plain objects with Redux-Logic. I believe that dispatching plain objects with Redux-Logic makes your code much easier to write and much easier to understand.
Redux-Thunk是Redux中间件的流行选择,它还允许您支持异步行为。 要使用Redux-Thunk处理异步行为,您的操作创建者必须返回函数 ,而不是使用Redux-Logic返回普通对象。 我相信使用Redux-Logic调度普通对象可以使您的代码更容易编写和理解。
Furthermore, I believe the ‘plain object’ approach for handling asynchronous behaviour fits more naturally alongside the rest of the (synchronous) Redux architecture, which makes this middleware fit in more organically with Redux.
此外,我相信用于处理异步行为的“普通对象”方法与(同步)Redux架构的其余部分更自然地契合,这使得该中间件与Redux更加有机地融合在一起。
Another popular Redux middleware is Redux-Saga. I found the learning curve of getting my head around sagas (a relatively new ES6 feature) quite steep when I looked at this option. This would be compounded if you wanted to introduce this library into an application managed by a team with several people. Additionally, I think that if they are not well managed, then sagas can create complicated-looking code compared to the Logic you create with redux-logic. This can impact development speed and code maintainability.
另一个流行的Redux中间件是Redux-Saga 。 当我查看此选项时,我发现绕开sagas(相对较新的ES6功能)的学习曲线相当陡峭。 如果您想将此库引入由几个人组成的团队管理的应用程序中,则情况会更加复杂。 另外,我认为,如果您对它们的管理不善,那么与使用redux-logic创建的Logic相比,sagas可以创建外观复杂的代码。 这会影响开发速度和代码可维护性。
示例概述 (Overview of example)
Below are simple snippets from a simple React application that can fetch the current weather conditions in a city and present it to the user. The example uses Redux-Logic to support asynchronous behaviour to fetch data using a free OpenWeatherMap API.
以下是一个简单的React应用程序中的简单代码段,可以获取城市中的当前天气状况并将其呈现给用户。 该示例使用Redux-Logic支持异步行为,以使用免费的OpenWeatherMap API获取数据。
For comparison, I have included a synchronous Redux process that displays the number of requests a user has made.
为了进行比较,我包括了一个同步Redux进程,该进程显示用户发出的请求数。
Here is the source code.
这是源代码。
搭建开发环境 (Setting up development environment)
These are the commands I ran to start creating my application:
这些是我开始创建应用程序时运行的命令:
npx create-react-app appnpm install --save reduxnpm install --save react-reduxnpm install --save redux-logicnpm install --save axios
And to see the app:
并查看该应用程序:
npm start
Happy that I could see the default Create React App homepage at localhost:3000, I then started writing some code!
很高兴能在localhost:3000看到默认的Create React App主页,然后我开始编写一些代码!
Below are code snippets that show the important points about integrating Redux-Logic into the project.
以下代码片段显示了有关将Redux-Logic集成到项目中的要点。
将中间件添加到我们的Redux商店 (Adding middleware to our Redux store)
In appStore.js, if we were not using any middleware, we would normally only provide our root reducer to the createStore method. This is where we link our Redux-Logic middleware to the rest of our application.
在appStore.js中 ,如果我们不使用任何中间件,则通常只将根缩减器提供给createStore方法。 这是我们将Redux-Logic中间件链接到其余应用程序的地方。
We specify that we want to use axios as our client for making HTTP requests.
我们指定我们要使用axios作为发出HTTP请求的客户端。
We then use a method from redux-logic to create our middleware and finally we add it as a parameter to the createStore method. This means our Redux code will be able to access our middleware. Great!
然后,我们使用redux-logic中的方法创建中间件,最后将其作为参数添加到createStore方法中。 这意味着我们的Redux代码将能够访问我们的中间件。 大!
调度异步动作 (Dispatching asynchronous actions)
With Redux-Logic, actions that trigger asynchronous behaviour are dispatched in the same way as actions that trigger synchronous state updates. There is nothing different!
使用Redux-Logic,触发异步行为的动作与触发同步状态更新的动作的分配方式相同。 没有什么不同!
For completeness, you can see below that when a user clicks on a button we call an action creator that has been passed to our component as props.
为了完整起见,您可以在下面看到,当用户单击按钮时,我们称为动作创建者,该动作创建者已作为道具传递给我们的组件。
拦截异步动作 (Intercepting Asynchronous actions)
This is where we first see the emergence of the redux-logic middleware coming into play. We are using the redux-logic library to create some ‘Logic’ that will intercept specified actions.
这是我们首先看到Redux逻辑中间件出现的地方。 我们正在使用redux-logic库来创建一些“逻辑”来拦截指定的动作。
In our Logic properties we tell redux-logic which action we want it to intercept. We specify that we want redux-logic to only provide data from the last action of this type that the component dispatched. In our example this declarative behaviour is useful if people keep clicking a button as they will get the value from the latest action they dispatched, not necessarily the last promise to return!
在逻辑属性中,我们告诉redux-logic我们希望它拦截哪个动作。 我们指定我们希望redux-logic仅提供组件分派的此类最后操作的数据。 在我们的示例中,如果人们不断单击按钮,则这种声明性行为很有用,因为他们将从派遣的最新操作中获得价值,而不一定是最后的诺言!
Next we specify that when the asynchronous process returns we immediately dispatch one of two actions. If the promise returned successfully, we return a GET_WEATHER_FOR_CITY_SUCCESSFUL action. This is what we want!
接下来,我们指定当异步进程返回时,我们立即 调度两个动作之一。 如果承诺成功返回,我们将返回GET_WEATHER_FOR_CITY_SUCCESSFUL动作。 这就是我们想要的!
Alternatively, if the promise returned was rejected then we dispatch GET_WEATHER_FOR_CITY_FAILURE.
或者,如果返回的承诺被拒绝,则我们将调度GET_WEATHER_FOR_CITY_FAILURE 。
This is where redux-logic really shines. It is clear what the intent of the Logic code is, and what is emitted are simple objects which are easy to read and interpret! I find this really easy to read, understand and debug.
这就是redux-logic真正发挥作用的地方 。 很明显,逻辑代码的意图是什么,发出的是易于阅读和解释的简单对象! 我发现这非常容易阅读,理解和调试。
At the bottom we make it clear what we want our asynchronous process to do. We want to return the value of a promise. Notice how we pass in the payload that came with our action into the URL.
在底部,我们明确说明了我们希望异步过程做什么。 我们要返回承诺的价值。 请注意,我们如何将动作附带的有效负载传递到URL中。
处理异步动作 (Processing Asynchronous actions)
You can see from the weatherDataHandling.js reducer that the actions dispatched from our Logic are then treated as plain object actions. Reducers mutate state in the same way as with synchronous actions. So the screenshot below is what you would expect from working with Redux before. Super!
您可以从weatherDataHandling.js精简器中看到,从我们的Logic派发的操作将被视为普通对象操作。 减速器以与同步动作相同的方式改变状态。 因此,下面的屏幕截图是您之前使用Redux所期望的。 超!
摘要 (Summary)
Redux is a popular predictable state container for JavaScript applications. By default all Redux actions support synchronous behaviour only, and you will need some kind of middleware solution for asynchronous behaviour.
Redux是JavaScript应用程序的一种流行的可预测状态容器。 默认情况下,所有Redux操作仅支持同步行为,并且您将需要某种中间件解决方案来实现异步行为。
Redux-Logic provides a clear and powerful middleware that allows you to use asynchronous actions in your Redux application. You add your middleware to your Redux Store to allow your application to use Redux-Logic. You use the redux-logic library to create Logic which intercepts particular actions and dispatches further actions after some asynchronous processing (like fetching data from an API) completes.
Redux-Logic提供了一个清晰而强大的中间件,使您可以在Redux应用程序中使用异步操作。 您将中间件添加到Redux Store,以允许您的应用程序使用Redux-Logic。 您可以使用redux-logic库来创建Logic ,该逻辑在某些异步处理(例如,从API提取数据)完成后,会拦截特定操作并调度其他操作。
All of the actions that are involved are plain object actions. I believe this makes it easier to write and easier understand compared with other solutions. Furthermore, redux-logic feels like a more organic fit with the other parts of the Redux architecture.
涉及的所有动作都是纯对象动作。 我相信,与其他解决方案相比,它更易于编写和理解 。 此外,redux-logic感觉与Redux架构的其他部分更加有机地契合。
Thanks for reading, I welcome any comments or questions below!
感谢您的阅读,我欢迎下面的任何评论或问题!
翻译自: https://www.freecodecamp.org/news/introduction-to-redux-logic-2f01c97d6c52/
redux logic
相关文章:

[SDOI2009]HH的项链
题目背景 无 题目描述 HH 有一串由各种漂亮的贝壳组成的项链。HH 相信不同的贝壳会带来好运,所以每次散步完后,他都会随意取出一段贝壳,思考它们所表达的含义。HH 不断地收集新的贝壳,因此,他的项链变得越来越长。有一…
DvaJS 入门, 快速上手Dva
为什么要使用Dva? React 没有解决的问题 React 本身只是一个 DOM 的抽象层,使用组件构建虚拟 DOM。 如果开发大应用,还需要解决一个问题。 通信:组件之间如何通信?数据流:数据如何和视图串联起来?路由…

Static、DynamicResource学习笔记一
定义了资源后,我们可以在元素中直接使用该资源,但又分为StaticResource及DynamicResource两种方式。 StaticResource 静态资源在首次创建窗口时一次性的设置完毕,之后源资源对象本身发生的任何变化都会影响到使用该资源的元素,如果…

javascript迭代器_JavaScript迭代器概述
javascript迭代器by Joanna Gaudyn乔安娜高登(Joanna Gaudyn) JavaScript迭代器概述 (An overview of JavaScript iterators) for,for…in和for…of循环之间的区别 (The difference between for, for…in and for…of loops) Iteration might be one of the most c…

knockout学习笔记目录
关于knockout学习系列的文章已经写完,这里主要是做个总结,并且将目录罗列出来,方便查看。欢迎各位大神拍砖和讨论。 总结 kncokout是一个轻量级的UI类库,通过MVVM模式使前端的UI简单话,减少javascript代码的编写。通常…

ant Design Pro 登录状态管理
未登录自动跳转到登录页面,登录成功不跳转回登录页面的实现代码调用流程。 ant Design Pro 是一个企业中后台管理框架,开始做他,第一个肯定是要做登录,下面来看一下它是怎么登录的。 先看路由配置 Authorized.jsx代码࿱…

初级java开发学习路线_成为初级全栈Web开发人员的10分钟路线图
初级java开发学习路线So you have started your journey into the world of web development. But what do you learn first? The Internet is overloaded with a wealth of information about the millions of different technologies that a web developer can know.因此&am…

国外物联网平台初探(四):Ayla Networks
定位 Ayla企业软件解决方案为全球部署互联产品提供强大的工具 功能 Ayla的IoT平台包含3个主要组成部分: (1) Ayla嵌入式代理Ayla Embedded Agents (2) Ayla云服务Ayla Cloud Services (3) Ayla应用库Ayla Application Libraries 设备 开发者使用任何微控制器、操作系…

《英语语法新思维初级教程》学习笔记(一)名词短语
参考资料: 1. 《英语语法新思维初级教程》 ▶ 知识点 ▼ 英语是“固定词序语言(a fixed-word-order language)”。 ▼ 语言的构造级别分五个层次:1. 词(word);2. 短语(phase…

根据数组中对象的属性值排序倒叙
数组中对象的属性值排序倒叙demo function compare(e) {return function (a, b) {var value1 a[e];var value2 b[e];return parseInt(value1) - parseInt(value2);} } var arr[{a:2},{a:3},{a:1}];var arr2 arr.sort(compare(time)).reverse();console.log(arr2) //[{a:3}…

!! javascript_产量! 产量! 生成器如何在JavaScript中工作。
!! javascriptby Ashay Mandwarya ?️??由Ashay Mandwarya提供吗? 产量! 产量! 生成器如何在JavaScript中工作。 (Yield! Yield! How Generators work in JavaScript.) If the title doesn’t already give a hint, we will be discussin…

ACM 竞赛高校联盟 练习赛 第二场 BC
B. 题解: 枚举约数即可,判断n个数能否填约数的整数倍 #include <iostream> #include <cstring> #include <cstdio> using namespace std; typedef long long LL; int main(){LL T, n, m;cin>>T;while(T--){cin>>n>>…

在一个数组中查找两个重复出现的数字
题目如下:现有一个数组长度为n1,里面存放有1到n-2,顺序不定,其中有两个数字出现了两次,现在要找出那两个数字。 例子A{2, 3, 1, 4, 5, 2, 4}, 这个数组长度为7,存放了1到5,但2和4出现…

React 组件生命周期
组件的生命周期可分成三个状态: Mounting:已插入真实 DOMUpdating:正在被重新渲染Unmounting:已移出真实 DOM 生命周期的方法有: componentWillMount 在渲染前调用,在客户端也在服务端。 componentDidMount : 在第一…

银行软件开发实习生_如何找到学生的软件开发人员实习生
银行软件开发实习生by Grazietta Hof由Grazietta Hof 如何找到学生的软件开发人员实习生 (How to find a Software Developer Internship as a student) Side note: Although this article is directed at students (because I am one so I can easily relate), I’m sure a l…

MAC OS X El CAPITAN 搭建SPRING MVC (1)- 目录、包名、创建web.xml
一、 下载STS(Spring Tool Suite) 官方地址:http://spring.io/tools/sts 下载spring tool suite for mac 最新版本。这个IDE是很不错的,其中spring插件已经配置好了。下载解压缩(一定要英文目录下)…

iOS小知识点记录
1>UITextField实现leftView: self.inputTextField [[UITextField alloc]initWithFrame:CGRectMake(10, 10, 200, 25)];self.inputTextField.delegate self;self.inputTextField.font [UIFont systemFontOfSize:15];self.inputTextField.placeholder " 想说点什么?…

Ant Design Pro 网络请求,视图绑定model并且渲染到页面 umi-request
封装网络请求,在service中新建接口,在model调用service,在视图绑定model并且得到网络请求的回调函数,获取网络请求的数据渲染到页面。 网络请求数据走向; 1.在utils/request.js 封装网络请求; /*** request 网络请求工具* 更详细的 api 文档: https://github.com/umijs…

2019机器学习比赛_2019顶尖的机器学习课程
2019机器学习比赛With strong roots in statistics, Machine Learning is becoming one of the most interesting and fast-paced computer science fields to work in. There’s an endless supply of industries and applications machine learning can be applied to to mak…

HTML5 canvas画图
HTML5 canvas画图 HTML5 <canvas> 标签用于绘制图像(通过脚本,通常是 JavaScript)。不过,<canvas> 元素本身并没有绘制能力(它仅仅是图形的容器) - 您必须使用脚本来完成实际的绘图任务。getCo…
排序算法7---快速排序算法
原理: 通过一趟排序将待排记录分割成独立的两部分,其中一部分记录的关键字均比另一部分记录的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序的目的。 #include <stdio.h> #define MAXSIZE 9typedef stru…

dispatch callback ant design pro 网络请求回调函数
index.jsx 代码解析:在组件初次渲染时调用 model 中 命名空间为 a_models 的 getData 网络请求,传了一个patload 参数和 callback 回调函数过去,然后通过 this.setState ()更新视图的 state。 import { Form, Tabs,Affix, Button,Input,Table } from antd; import Re…

bigquery使用教程_如何使用Python和Google BigQuery构建机器人以自动执行您的笨拙任务...
bigquery使用教程Do you have repetitive tasks? Something that you do regularly, every week or even every day? Reporting might be one of your weekly or daily tasks. You query or ask for the data, and do some visualizations, then give it to your boss. What …

5S后返回首页
1 <!DOCTYPE html>2 <html>3 <head>4 <title>5S后返回首页</title> 5 <meta http-equiv"Content-Type" content"text/html; charsetgkb"/> 6 </head>7 <body>8 <h2>操作成功</h2>…
TypeScript 1
TypeScript 的由来 TypeScript 是 JavaScript 的一个超集,支持 ECMAScript 6 标准。 TypeScript 由微软开发的自由和开源的编程语言。 TypeScript 设计目标是开发大型应用,它可以编译成纯 JavaScript,编译出来的 JavaScript 可以运行在任何…

大龄屌丝自学笔记--Java零基础到菜鸟--028
泛型,for循环增强应用,静态导入,可变参数,asList() 1、泛型 约束了数据类型,格式为 <数据类型>,如:ArrayList<int> aListnew ArrayList<int>(); 泛型通配符:<?…

c# typescript_在任何IDE中从C#,Java或Python代码获取TypeScript接口的简单方法
c# typescriptby Leonardo Carreiro莱昂纳多卡雷罗(Leonardo Carreiro) 在任何IDE中从C#,Java或Python代码获取TypeScript接口的简单方法 (The easy way to get TypeScript interfaces from C#, Java, or Python code in any IDE) Who has never experi…

js里的document对象大全(DOM操作)
什么是DOM document object model 的简称,意思为文档对象模型。主要用来对文档中的html节点进行操作。 Dom的操作简单示例: <div id"t1"><div><input type"file" /> <input type"button" value"…

【制作镜像】BCEC制作镜像
如要制作的新镜像已存在标准版本镜像,即linux发行版本相同(此处指CentOS6.5 64位),可利用BCEC制作。 在BCEC创建centos6.5系统的可联外网的虚机,ssh到此虚机,用yum方式安装所需的功能: yum&…

Ant Design Pro 组件事件绑定 Input onChange
Input 组件的 onChange 事件绑定语法 render() {this.shop_change e > {const { value } e.target;console.log(shop_change,value)};return (<Input placeholder"" onChange{this.shop_change}></Input>)}