current position:Home>Understanding of compose in Redux
Understanding of compose in Redux
2022-05-15 07:50:21【User 4669777】
application
I gave it to myself recently react
Project add redux
When , Yes redux
Medium compose
function , Use compose
To enhance store
, Here is an application I used in the project :
import {createStore,applyMiddleware,compose} from 'redux';
import createSagaMiddleware from 'redux-saga';
const sagaMiddleware = createSagaMiddleware();
const middlewares = [];
let storeEnhancers = compose(
applyMiddleware(...middlewares,sagaMiddleware),
(window && window .devToolsExtension) ? window .devToolsExtension() : (f) => f,
);
const store = createStore(rootReducer, initialState={} ,storeEnhancers);
The above code can make store
And applyMiddleware
and devToolsExtension
Use it together .
reduce Method
Understanding compose
Before the function, let's know what is reduce
Method ? That's what the official document defines reduce
Methodical :
reduce()
Method for each element in the accumulator and array ( From left to right ) Apply a function , Simplify it to a single value .
Look at the function signature :
arr.reduce(callback[, initialValue])
callback
Functions that execute each value in the array , There are four parameters :
accumulator
( accumulator ) The accumulator accumulates the return value of the callback ; It is the cumulative value returned when the callback was last called , orinitialValue
.currentValue
( Current value ) The element being processed in the array .currentIndex
Optional ( Current index ) The index of the current element being processed in the array . If provided initialValue, Then the index number is 0, Otherwise, the index is 1.array
Optional ( Array ) call reduce() Array ofinitialValue
Optional ( Initial value ) Used as the first callcallback
The value of the first parameter of . If no initial value is provided , Then the first element in the array... Will be used . There is no beginning Call... On an empty array of starting valuesreduce
Will be an error .
Let's take a look at a simple :
Array sum
var sum = [0, 1, 2, 3].reduce(function (a, b) {
return a + b;
}, 0);
// sum The value is 6
This is a simple example , Let's take a slightly more complicated example , Count the number of occurrences of each element in the array :
var series = ['a1', 'a3', 'a1', 'a5', 'a7', 'a1', 'a3', 'a4', 'a2', 'a1'];
var result= series.reduce(function (accumulator, current) {
if (current in accumulator) {
accumulator[current]++;
}
else {
accumulator[current] = 1;
}
return accumulator;
}, {});
console.log(JSON.stringify(result));
// {"a1":4,"a3":2,"a5":1,"a7":1,"a4":1,"a2":1}
This example makes clever use of the of arrays reduce
Method , It is also often used in many algorithmic interview questions . Note here that you need to specify initialValue
Parameters .
adopt reduce
Function can also realize array de duplication :
var a = [1, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7];
Array.prototype.duplicate = function() {
return this.reduce(function(cal, cur) {
if(cal.indexOf(cur) === -1) {
cal.push(cur);
}
return cal;
}, [])
}
var newArr = a.duplicate();
compose function
After understanding the array reduce
After method , It's easy to understand compose
Function , Because actually compose
With the help of reduce
To achieve . Look at the official source code :
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
The return value of is also a function , The parameters passed by calling this function will be used as compose
The parameter of the last parameter , So it looks like " Onion rings " like , From the inside out , Step by step call .
See the following example :
import { compose } 'redux';
// function f
const f = (arg) => ` function f(${arg})`
// function g
const g = (arg) => ` function g(${arg})`
// function h The last function can accept multiple parameters
const h = (...arg) => ` function h(${arg.join('_')})`
console.log(compose(f,g,h)('a', 'b', 'c')) // function f( function g( function h(a_b_c)))
So the final return is such a function compose(fn1, fn2, fn3) (...args) = > fn1(fn2(fn3(...args)))
.
copyright notice
author[User 4669777],Please bring the original link to reprint, thank you.
https://en.chowdera.com/2022/131/202205102047501204.html
The sidebar is recommended
- Which securities company does qiniu school recommend? Is it safe to open an account
- Hyperstyle: complete face inversion using hypernetwork
- What activities are supported by the metauniverse to access reality at this stage?
- P2P swap OTC trading on qredo
- Google | coca: the contrast caption generator is the basic image text model
- SIGIR 2022 | Huawei reloop: self correcting training recommendation system
- Whether you want "melon seed face" or "national character face", the "face changing" technology of Zhejiang University video can be done with one click!
- Sorting of naacl2022 prompt related papers
- Servlet create project
- "Chinese version" Musk was overturned by the original: "if it's true, I want to see him"
guess what you like
[network security] web security trends and core defense mechanisms
[intensive reading] object detection series (10) FPN: introducing multi-scale with feature pyramid
007. ISCSI server chap bidirectional authentication configuration
2021-03-09
plot_ Importance multi classification, sorting mismatch, image value not displayed
[intensive reading] object detection series (XI) retinanet: the pinnacle of one stage detector
How to install MFS environment for ECS
[intensive reading] the beginning of object detection series (XII) cornernet: anchor free
Open source sharing -- a record of students passing through time
MOT:A Higher Order Metric for Evaluating Multi-object Tracking
Random recommended
- How to develop a distributed memory database (1)
- Reverse engineers reverse restore app and code, and localization is like this
- One line command teaches you how to export all the libraries in anaconda
- Bi tools are relatively big. Let's see which one is most suitable for you
- Read the history of database development
- Self cultivation of coder - batterymanager design
- Technology application of swift phantom type phantom in Apple source code learning
- Swiftui advanced skills: what is the use of the technology of swift phantom type phantom
- Swiftui advanced animation Encyclopedia of complex deformation animation is based on accelerate and vector arithmetic (tutorial includes source code)
- What problems remain unsolved in swiftui in 2022
- I'll set the route for fluent
- Flutter drawing process analysis and code practice
- Emoji language commonly used icon collection (interesting Emoji)
- 5.14 comprehensive case 2.0 - automatic induction door
- How to deploy redis service on k8s top?
- Importance of data warehouse specification
- Idea automatically generates serialization ID
- Why is it recommended not to use select * in MySQL?
- Let's talk about why redis needs to store two data structures for the same data type?
- Domain lateral move RDP delivery
- gDvuGqjmDS
- [learn slam orb_slam2 or slam3 from scratch] summary of all blog articles
- 20000 + star ultra lightweight OCR system pp-ocrv3 effect increased by 5% - 11%!
- A configurable canvas clock - Super multi style
- The pp-ocrv3 effect of 20000 + star ultra lightweight OCR system is further improved by 5% - 11%
- MySQL's golden rule: "don't use select *"
- True interview question: why does redis store a data type twice?
- High threshold for large factories? Five exclusive PDFs inside Alibaba will take you forward and win the offer
- Is it really hard to find a job? How on earth can I find a job with high salary without worrying about being laid off
- How to design knowledge center? (code attached)
- OWASP top 10 vulnerability analysis
- Are you still writing comment templates manually? Idea can generate annotation templates of classes and methods with one click. Click in if you don't know
- Numpy core syntax and code sorting summary!
- Can you believe that the swoole timer can realize millisecond task scheduling?
- Detailed explanation of art template engine
- Telephone subsystem of openharmony source code analysis -- call flow
- Yixin Huachen: how to do a good job in digital transformation in the power industry?
- One stop collaboration is really delicious - apipost
- Notes on modern algebra and series of questions: Chapter 1 (introduction of algebraic system)
- Notes on modern algebra and serialization of question types: Chapter 2 (properties of binary operation)