简体   繁体   中英

What is this chained ES6 arrow function?

I am creating an app using React, Redux.

Among them, I am making a Redux middleware,

There is a part that I do not understand.

Here is the code:

const loggerMiddleware = store => next => action => {

    console.log('currentState', store.getState());

    console.log('action', action);

    const result = next(action);

    console.log(', store.getState());
    console.log('\n'); 

    return result;
}

export default loggerMiddleware; 

What is this arrow function => => => ? It does not make sense that the arrow function continues.

What does that mean?

The code below:

const loggerMiddleware = store => next => action => { 
    var result = /* .. */
    return result;
}

is the equivalent of:

const loggerMiddleware =  function(store) { 
    return function(next) {
        return function(action) {
            return result;
        }
    }
}

This is a technique (called currying) that replaces a single function which takes some arguments with multiple functions each taking a part of those arguments, for example:

  const f1 = (x, b) => x + b; const f2 = x => b => x + b; const f1Result = f1(1, 2); // we can construct f2's result in multiple steps if we want because it returns a function, this can be helpful. let f2Result = f2(1); f2Result = f2Result(2); console.log('f1Result', f1Result); console.log('f2Result', f2Result); 

You can also read this for more insight of the rationale behind this decision, mainly:

Sometimes we want to associate some local state with store and next

Javascript arrow function is the replacement of 8 characters 'function' keyword. you don't need to write return within your function when you are using arrow function.

As per Javascript best practices try to use when you are making service calls. It is used as function keyword short hand.

For more on this see a good sample on this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM