current position:Home>Understanding of compose in Redux

Understanding of compose in Redux

2022-05-15 07:50:21User 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 , or initialValue.
  • 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 of
  • initialValue Optional ( Initial value ) Used as the first call callback 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 values reduce 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

Random recommended