1. Let’s start with higher-order functions. Higher-order functions solve the problem of abstracting out a certain cross section. And the next two methods, add, do a separate addition, and let’s add all of our additions. This not only ensures that the add operation is not contaminated, but also supports part of our business logic, which is addFive,addTen.

function add(p,q){
	return p+q
}

function addFive(x,fn){
	return fn(x,5)
}

function addTen(x,fn){
	return fn(x,10)
}



addFive(1,add)     // 6

addTen(1,add)     // 11
Copy the code

You might say, well, why don’t you just write it down like this?

Function add(a,b){return a+b} add(1,5) //6Copy the code

You can, but you can make it a little bit more complicated,

Let the PEI = 1.1314926... ; function addPEI(a,b){ return a+b } function add2PEI(a,b){ return a+2*b } addPEI(1,PEI) add2PEI(1,PEI)Copy the code

This PEI is our requirement, and as you can see from this, I have to use PEI every time, unchanged, which is probably more complicated than infinite unlooping. So let’s do something similar. We still have to deal with complex requirements like PEI, but again, the result is a+b addition logic (similar to map’s for loop). Have we found the advantage of the original method, we can take the addition logic out of our business, so it is called PEI and 2PEI?

Function add(p,q){return p+q} function addPEI(a,fn){let PEI = 1.1314926......... ; Return fn(a,PEI)} function add2PEI(a,fn){let PEI = 1.1314926......... ; return fn(a,2*PEI) }Copy the code

In this way, I no longer care how complex PEI is, just call addPEI, add2PEI, and PEI can be viewed as a block of code similar to, but extremely complex, business code in the project.

But you can also see that we’re still writing a lot of duplicate code here. As mentioned above, PEI and 2*PEI are complex logic, so we can separate this part out as well.

Let the PEI = 1.1314926... ; function add(p,q){ return p+q } function addMaker(a,fn){ return (b)=>{ fn(a,b) } } // let addPEI = addMaker(1,add)(PEI) let addPEI = addMaker(1,add); addPEI = (b)=>{ add(1,b) } addPEI(PEI) = add(1,PEI) // let add2PEI = addMaker(1,add)(2*PEI)Copy the code

So far, the higher-order components are pretty much the same, and the higher-order components basically do two things for us. 1. Reuse complex code. For a piece of code, reuse the code by passing parameters, like PEI 2. Reuse complex logic, like the a+ B part of the logic above

Hoc (a,fn)=>{
	return (b)=>fn(a,b)
}

Hoc(1,fn)(2)
Copy the code

This code also does that for us. It can reuse logic as well as code

2. For higher-order components, is it the same thing? We pull out a component and reference it in multiple places. This code is PEI

The same page uses a different PEI, but this page is still a+ B logic.

Examples: Advanced component references: Map, Filter, Withrouter

Return higher-order functions of higher-order components: see connect(mapprops, mapState)(List);