第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > redux logic_Redux-Logic简介

redux logic_Redux-Logic简介

时间:2021-12-06 03:27:20

相关推荐

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 makingpredictablestate 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 callaction creatorswhich dispatchactions. 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 byreducers. 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 willtake a copyof the application state,mutatethecopy(according to the action and its payload) and then update the state in the applicationStore.

应用程序状态由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 particularplain objectactions, perform asynchronous processing and then dispatch anotherplain 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 areplain objects. The action that is dispatched by the UI component and the action that is then dispatched by the Logic willalwaysbe 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-Thunkis 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 toreturn functionsas 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 isRedux-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 atlocalhost: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)

InappStore.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 useaxiosas 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 weimmediatelydispatchone of two actions. If the promise returned successfully, we return aGET_WEATHER_FOR_CITY_SUCCESSFULaction. This is what we want!

接下来,我们指定当异步进程返回时,我们立即调度两个动作之一。 如果承诺成功返回,我们将返回GET_WEATHER_FOR_CITY_SUCCESSFUL动作。 这就是我们想要的!

Alternatively, if the promise returned was rejected then we dispatchGET_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 theweatherDataHandling.jsreducer that the actions dispatched from our Logic are then treated as plain object actions. Reducers mutate state in thesame 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 aclearandpowerfulmiddleware that allows you to use asynchronous actions in your Redux application. You add your middleware to your ReduxStoreto allow your application to use Redux-Logic. You use the redux-logic library to createLogicwhich intercepts particular actions and dispatches further actions after some asynchronous processing (like fetching data from an API) completes.

Redux-Logic提供了一个清晰强大的中间件,使您可以在Redux应用程序中使用异步操作。 您将中间件添加到ReduxStore,以允许您的应用程序使用Redux-Logic。 您可以使用redux-logic库来创建Logic,该逻辑在某些异步处理(例如,从API提取数据)完成后,会拦截特定操作并调度其他操作。

All of the actions that are involved areplain objectactions. I believe this makes iteasier to writeandeasier understandcompared 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!

感谢您的阅读,我欢迎下面的任何评论或问题!

翻译自: /news/introduction-to-redux-logic-2f01c97d6c52/

redux logic

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。