This time I will show you how to use react redux and what are the precautions for using react redux. The following is a practical case, let's take a look.
Students who have used react all know the existence of redux. Redux is a front-end warehouse used to store data and a framework for adding, deleting, modifying and checking the warehouse. It is not only applicable to react , also used in other front-end frameworks. Anyone who has studied the redux source code thinks that the source code is very sophisticated, and this blog post will introduce the processing of middleware in redux.
Before talking about redux middleware, let’s use two pictures to briefly introduce the basic principles of redux:
The picture shows the basic process of redux. I won’t go into details here.
Generally, not only redux is used in react, but also react-redux:
react-redux will not be detailed here.
redux middleware
Under normal circumstances, redux does not have the ability to handle asynchronous requests. Young communication is done indirectly or by adding middleware to strengthen dispatch. The ability is that redux has the ability to be asynchronous;
Generally speaking, there are two ways for redux to handle asynchrony: indirect method and middleware method;
Indirect method:
The indirect method is to customize the asynchronous behavior and retain the dispatch synchronization function.
Idea: The asynchronously returned result is stuffed into the action, and then synchronized to the reduce through dispatch, and then the state is changed;
demo:
request.get(API) .then(d => { store.dispatch(type: xxx, playload: d) })
This method does not destroy the synchronization mechanism of dispatch. It uses dispatch to synchronize data to the state. However, the disadvantage is that each call will write a long paragraph.
Middleware method
The core part of the middleware method is the high-order function applyMiddleWare provided by redux, which returns a brand new store object through multiple layers of calls. The only difference between the new store object and the original object is that dispatch has the asynchronous function;
Source code:
const applyMiddleWare = (...middlewares) => createStore => (reducer, initState) =>{ const store = createStore(reducer, initState); const _dispatch = store.dispatch; const MiddleWareAPI = { getState: store.getState, dispatch: action => _dispatch(action) 1) }; const chain = []; chain = middlewares.map(middleware => {middleware(MiddleWareAPI)}); 2) let dispatch = compose(...chain)(store.dispatch); 3) return { dispatch, ...store } }
It is just a dozen lines of code, but it contains many subtleties. Here, the blogger chose three of them to analyze their subtleties:
1) MiddleWareAPI is mainly inserted into middleware, and finally inserted into the action, so that the action can have the dispatch ability, and The main reason why anonymous functions are used here is because the store in MiddleWareAPI.dispatch must be consistent with the store finally returned by applyMiddleWare. It should be noted that MiddleWareAPI.dispatch does not really change the state. It can be understood as action and middleware. of a bridge.
2) The change is to insert MiddleWareAPI into all middleware, and then return a function, and the form of middleware will be mentioned later.
3) This is the most subtle point. Compose will inject the chain array from right to left into the previous middleware, while store.dispatch will inject into the rightmost middleware. In fact, compose can be understood as a reduce function here.
eg:
M = [M1,M2,M3] ----> M1(M2(M3(store.dispatch)));
From here you can actually know what middleware looks like:
Basic form of middleware:
const MiddleWare = store => next => action => { ... }
Parameter explanation:
store: Actually it is MiddleWareAPI;
next: There are two situations here. If the middleware is changed to the rightmost part of the middlewares array, Then next is store.dispatch; otherwise it is the return value of a middleware on the adjacent left (the closure function is the action => {} function);
- ##action: OK It can be a function or an object containing a promise;
next(非最右边的中间件):其实就是相邻前一个中间件返回的函数(action => {...});这里的action就是上一级中间件next(action)中的action,第一个中间件的action就是项目中store.dispatch(action)中的action。
中间件中的store.dispatch:其实就是用来塞进action的,这里就理解为action和中间件通信的渠道吧。
流程图:
demo:
export const MiddleForTest = store => next => action => { if (typeof action === 'function') { action(store); } else { next(action); } }; export const MiddleForTestTwo = store => next => action => { next(action); }; export function AjaxAction(store) { setTimeout(function () { store.dispatch({ type: 'up', playload: '异步信息' }) }, 1000) } store.dispatch(AjaxAction);
说道这里应该会对中间件有个大致的认识,接下来介绍一下常用的中间件以及自己写一个中间件。
redux-thunk:主要是适用于action是一个函数的情况,它是对原有的中间件模式再封装多一层,原则上是支持promise为主的action函数;
export function AjaxThunk (url, type) { return dispatch => { Ajax(url) .then(d => { dispatch({ type, playload: d }) }) } } store.dispatch(AjaxThunk(url1, 'add'));
redux-promise:主要就是针对action对象,action对象是一个promise的异步请求函数:
它的大概实现思路是:
const promiseAction = store => next => action => { const {type, playload} = action; if (playload && typeof playload.then === 'function') { playload.then(result => { store.dispatch({type, playload: result}); }).catch(e => {}) } else { next(action); } } action = { type: 'xxx', playload: Ajax(url) }
自定义中间件:很多时候网上的redux中间件可能不太符合项目中的需要,所以这时候可以自己写一套适合项目的中间件,以下指示本博主的一个demo,形式不唯一:
export const PromiseWares = store => next => action => { next({type: 'right', playload: 'loading'}); if (typeof action === 'function') { const {dispatch} = store; action(dispatch); } else { const {type, playload} = action; if (playload && typeof playload.then === 'function') { playload.then(result => { store.dispatch({type, playload: result}); }).catch(e => {}) } else { next(action); next({type: 'right', playload: 'noLoading'}); } } };
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to use react+redux. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor