Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand and master Redux

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to understand and master Redux". In daily operation, I believe many people have doubts about how to understand and master Redux. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts of "how to understand and master Redux"! Next, please follow the editor to study!

1. Why Redux

Before we talk about why we use Redux, let's talk about how components communicate. There are several common ways for components to communicate:

Parent and child components: props, state/callback callback to communicate

Single-page applications: routing values

Global events such as EventEmitter snooping callback pass value

Cross-level component data transfer Context (context) in react

In small and less complex applications, it is generally sufficient to use the above components to communicate.

However, with the increasing complexity of the application, too many data states (such as server response data, browser cache data, UI status values, etc.), and the state may change frequently, using the above components to communicate will be very complex, tedious and difficult to locate and debug related problems.

Therefore, the state management framework (such as Vuex, MobX, Redux, etc.) is very necessary, and Redux is one of the most widely used and ecologically perfect.

II. Redux Data flow

In an App application that uses Redux, you will follow these four steps:

Step 1: triggering an action,action through store.dispatch (action) is an object that describes what is going to happen. As follows:

BindActionCreator simplifies the process of sending actions. When the returned function is called, dispatch is automatically called to send the corresponding action.

BindActionCreators does different processing according to different types of actionCreators. If actionCreators is a function, it returns a function, and if it is an object, it returns an object. The main purpose is to convert actions to dispatch (action) format, which facilitates the separation of actions and makes the code more concise.

5. Compose.js/** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @ param {... Function} funcs The functions to compose. * @ returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose (f, g, h) is identical to doing * (... args) = > f (g (h (.args). * / export default function compose (... funcs) {if (funcs.length = 0) {return arg = > arg} if (funcs.length = 1) {return funcs [0]} return funcs.reduce ((a, b) = > (... args) = > a (b (.args)}

Compose is a very important concept in functional transformation. Before introducing compose, what is Reduce? As defined in the official documentation, the reduce:reduce () method applies to each element in the accumulator and array (from left to right) to a function, reduced to a value. Compose is a Corialized function, which is implemented with the help of Reduce, merging multiple functions into a single function return, mainly used in middleware.

6. ApplyMiddleware.js/** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * / export default function applyMiddleware (... middlewares) {return createStore = > (... args) = > {const store = createStore (... args). Return {... store, dispatch}

ApplyMiddleware.js file provides middleware middleware important API,middleware middleware is mainly used to rewrite store.dispatch to improve and expand the function of dispatch.

Then why do you need middleware?

First of all, let's start with Reducer. It was mentioned in the previous three principles of Redux that reducer must be a pure function. The definition of pure function is given below:

Return the same result for the same parameter

The result depends entirely on the parameters passed in

Without any side effects.

As for why reducer must be a pure function, we can start with the following points?

Because Redux is a predictable state manager, pure functions are more convenient for Redux debugging, can more easily track and locate problems, and improve development efficiency.

Redux only compares the addresses of old and new objects to see if the two objects are the same, that is, through a shallow comparison. If you modify the property value of the old state directly inside the Reducer, both the new and old objects point to the same object, and if you still make a shallow comparison, it will cause Redux to think that it has not changed. However, through deep comparison, it will consume a lot of performance. The best way is for Redux to return a new object, and the old and new objects are compared, which is an important reason why Reducer is a pure function.

Reducer is a pure function, but it still needs to handle logging / exception, asynchronous handling and other operations in the application, so how to solve these problems?

The answer to this question is middleware. The functionality of dispatch can be enhanced through middleware. Examples (logging and exceptions) are as follows:

Const store = createStore (reducer); const next = store.dispatch; / / rewrite store.dispatchstore.dispatch = (action) = > {try {console.log ('action:', action); console.log (' current state:', store.getState ()); next (action); console.log ('next state', store.getState ());} catch (error) {console.error (' msg:', error) Fifth, implement a simple Redux from scratch

Since we are going to implement a Redux (simple counter) from scratch, let's forget the concepts such as store, Reducer, dispatch, and so on, and just keep in mind that Redux is a state manager.

First, let's take a look at the following code:

Let state = {count: 1} / / console.log (state.count) before modification; / / change the value of count to 2state.count = 2ramp / console.log (state.count) after modification

We define a state object with a count field, and can output the count value before and after modification. But at this point we will find a problem? Other places that refer to count do not know that count has been modified, so we need to listen through the subscription-publish mode and notify other places that refer to the count. So we further optimize the code as follows:

Let state = {count: 1}; / / subscribe to function subscribe (listener) {listeners.push (listener);} function changeState (count) {state.count = count; for (let I = 0; I

< listeners.length; i++) { const listener = listeners[i]; listener();//监听 }} 此时我们对count进行修改,所有的listeners都会收到通知,并且能做出相应的处理。但是目前还会存在其它问题?比如说目前state只含有一个count字段,如果要是有多个字段是否处理方式一致。同时还需要考虑到公共代码需要进一步封装,接下来我们再进一步优化: const createStore = function (initState) { let state = initState; //订阅 function subscribe (listener) { listeners.push(listener); } function changeState (count) { state.count = count; for (let i = 0; i < listeners.length; i++) { const listener = listeners[i]; listener();//通知 } } function getState () { return state; } return { subscribe, changeState, getState }} 我们可以从代码看出,最终我们提供了三个API,是不是与之前Redux源码中的核心入口文件index.js比较类似。但是到这里还没有实现Redux,我们需要支持添加多个字段到state里面,并且要实现Redux计数器。 let initState = { counter: { count : 0 }, info: { name: '', description: '' }}let store = createStore(initState);//输出countstore.subscribe(()=>

{let state = store.getState (); console.log (state.counter.count);}); / / output infostore.subscribe (() = > {let state = store.getState (); console.log (`${state.info.name}: ${state.info.description}`);})

Through testing, we found that multiple attribute fields are now supported in state. Next, we modify the previous changeState so that it can support self-increment and self-subtraction.

/ / self-increasing store.changeState ({count: store.getState (). Count + 1}); / self-decreasing store.changeState ({count: store.getState (). Count-1}); / / changing it to whatever store.changeState ({count: finance})

We find that we can increase, decrease or change it casually through changeState, but this is not really what we need. We need to constrain the modification of count, because we are implementing a counter that must only want to add and subtract. So let's next constrain changeState, agree on a plan method, and do different processing according to type.

Function plan (state, action) = > {switch (action.type) {case 'INCREMENT': return {... state, count: state.count + 1} case' DECREMENT': return {... state, count: state.count-1} default: return state}} let store = createStore (plan, initState); / / add store.changeState ({type: 'INCREMENT'}) / / self-subtracting store.changeState ({type: 'DECREMENT'})

We have done different treatments for different type in the code, at this time we found that we can no longer modify the count in state casually, we have successfully constrained the changeState. We take the plan method as the input parameter of the createStore and follow the plan method when we modify the state. So far, congratulations, we have implemented a simple counter in Redux.

This is the realization of Redux? Why is this different from the source code?

Then we replace plan with reducer and changeState with dispatch, and we will find that this is the basic function achieved by the Redux source code. Now look back to see if the data flow diagram of Redux is clearer.

VI. Redux Devtools

Redux devtools is a debugging tool for Redux, and the corresponding plug-ins can be installed on Chrome. For applications connected to Redux, it is convenient to see the changes after each request through Redux devtools, and it is convenient for developers to know the causes and consequences after each operation, which greatly improves the efficiency of development and debugging.

As shown in the figure above, the visual interface of Redux devtools. The operation interface on the left is the action executed during the rendering of the current page, and the interface on the right is the data stored by State. You can view the Reducer parameters corresponding to action by switching from State to action panel. Switch to the Diff panel to view the property values that have changed before and after the two operations.

At this point, the study of "how to understand and master Redux" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report