当前位置:网站首页>Change your posture to look at hooks, the combination of inspiration sources and the separation of new ideas from logical view in hoc mode
Change your posture to look at hooks, the combination of inspiration sources and the separation of new ideas from logical view in hoc mode
2022-04-23 00:46:00 【CSDN cloud computing】

author |
source | front end Sharing

Preface
Understand JSX In essence, students know that it is just a kind of grammar sugar , Will be babel Processing into createElement In the form of , Finally, it becomes routine js object . therefore , We can do that js Logical level element Object processing , Customize hooks As element Logic processing layer , It becomes a matter of course .
In this paper, we will study , Customize hooks Some other uses of , And how to deal with view layers , There are some new ways to play .

use hooks Handle element object
Scene one
hooks Handle element There are many cases of . For example, we are relatively UI Cache the contents of the layer , Like the following scene .
function Test(){
console.log('test rerender')
return <div>
hello, react !
</div>
}
function Index({ value }){
const [ number , setNumber ] = React.useState(0)
const element = React.useMemo(()=> <Test /> ,[ value ])
return <div>
{element}
<button onClick={() => setNumber(number +1 )} > Click on {number} </button>
</div>
}
Use as above useMemo Cache handling Test Component corresponding element object , When Index Medium value When things change , Will be executed again useMemo Get new element object .
When the button is clicked , Will trigger setNumber change state, Will trigger Index Update , however useMemo It will directly read the cached value , This performance experience is Test No more updates .
It's based on hooks Optimization strategy for the implementation of , In essence, it is right to element The cache of . After this scheme is processed Index No longer need to be similar to HOC Of memo Package of components . According to the condition and direction , Do optimization in the direction of customization in rendering , This is a kind of father -> The optimization scheme of sub .
There are some more complex scenes , That's more than one. hooks combined , To achieve the goal .
function Index(){
const [ number , setNumber ] = React.useState(0)
const { value } = React.useContext(valueContext)
const element = React.useMemo(()=> <Test /> ,[ value ])
return <div>
{element}
<button onClick={() => setNumber(number +1 )} > Click on {number} </button>
</div>
}
adopt useContext Read valueContext Medium value attribute , Test Component subscription value The change of , When context Inside value When things change , To regenerate the element object , That is to re render Test Components .
Scene two
react router v6 After coming out , There's a whole new hooks —— useRoutes. It can accept the configuration of routing js Routing tree , Returns the of a view layer element tree. Let's take a look at the specific use .
const routeConfig = [
{
path:'/home',
element:<Home />
},
{
path:'/list/:id',
element:<List />
},
{
path:'/children',
element:<Layout />,
children:[
{ path:'/children/child1' , element: <Child1/> },
{ path:'/children/child2' , element: <Child2/> }
]
}
]
const Index = () => {
const element = useRoutes(routeConfig)
return <div className="page" >
<div className="content" >
<Menus />
{element}
</div>
</div>
}
const App = ()=> <BrowserRouter><Index /></BrowserRouter>
useRoutes For customization hooks , Returns the normalized routing structure .hooks No longer only responsible for logical processing as we usually do , In this scenario ,hooks Completely acts as a view container .
In this mode , For customization hooks Understanding breaks traditional ideas , Maybe this transformation from logical layer to view layer , It will make some students uncomfortable , But it doesn't matter , We need a change in thinking , That's what matters .

Design patterns
Now imagine a scenario , Customize hooks Can you implement a design scenario , Can be similar to composite patterns and hoc The combination of patterns , It can realize the separation of logic and view ?
1、 The disadvantages of traditional combination mode
First, let's look at the combination mode , The traditional combination mode is as follows :
function Index(){
return <GrandFather>
<Father>
<Son>{null}</Son>
</Father>
</GrandFather>
}
Through the top GrandFather , Father, Son Three components are combined . In this mode , If the inner and outer components of the combination need to establish association and communication , Need to pass through cloneElement Mixed with some communication methods .
Take the above as an example , If you want to achieve Father <——> Son Two-way communication , We need to do this :
/* Parent component */
function Father({ children }){
const [ fatherSay , setFatherSay ] = React.useState('')
const toFather= ()=> console.log('son to father')
const element = React.cloneElement(children,{ fatherSay ,toFather })
return <div>
<p> Father </p>
<button onClick={() => setFatherSay('father to son')} >to Son</button>
{element}
</div>
}
/* Child components */
function Son({ children, fatherSay, toFather }){
console.log(fatherSay)
return <div>
<p> son </p>
<button onClick={toFather} >to Father</button>
{children || null}
</div>
}
Above
Father Components through
cloneElementtowards props Mixed intoFatherMethod .Son Components can be passed directly through props Get this method and communicate with the parent component , Realization Son -> Father.Father Can pass
useStatechange fatherSay And pass it on to Son, Realization Father -> Son.
One obvious drawback is :
toFather ,cloneElement Such logic needs to be handled by developers alone , That is, the logical layer and ui Layers are strongly correlated . This requires developers to , The logic is processed separately in the upper and lower components of the composite mode .
If you add GrandFather Components , Then you need to deal with it like the following figure :
2、hoc Nested provision idea
hoc It's a function in itself , Receive the original component , Return to the new component , Multiple hoc Can be nested .
function Index(){
/* .... */
}
export default HOC1(styles)(HOC2( HOC3(Index) ))
HOC1 -> HOC2 -> HOC3 -> Index
Then can I use hoc This idea , To implement the composite pattern , And solve logical redundancy .
3、 Use custom hooks Realization
Combined with what I said at the beginning , You can customize hooks To deal with it ui Logic , Then you can pass something like hoc Multiple nesting of hooks, Solve the above defects of the combination mode .
So custom hooks The design is as follows :
useComposeHooks( component, Layout , mergeProps )
component For components that need to be processed through composite mode .
Container components that need to be combined .
mergeProps New that needs to be merged props .
useComposeHooks You can use multiple nested . Such as the following :
function Index(){
const element = useComposeHooks( useComposeHooks( useComposeHooks(...) , Layout2,mergeProps ) ,Layout1,mergeProps)
return element
}
Equivalent to :
<Layout1>
<Layout2>
{ ... }
</Layout2>
</Layout1>
Next, let's implement this function .

Code implementation and effect verification
1、 To write useComposeHooks
Next let's write useComposeHooks:
function useComposeHooks(component, layout, mergeProps) {
const sonToFather = useRef({})
const fatherToSon = useRef({})
/* Child to parent component communication */
const sonSay = React.useCallback((type, payload) => {
const cb = sonToFather.current[type]
typeof cb === 'function' && cb(payload)
}, [component])
/* Parent and child components */
const listenSonSay = React.useCallback((type, fn) => {
sonToFather.current[type] = fn
}, [layout])
/* Parent to child component communication */
const fatherSay = React.useCallback((type,payload)=>{
const cb = fatherToSon.current[type]
typeof cb === 'function' && cb(payload)
},[layout])
/* The child listens to the parent component */
const listenFather = React.useCallback((type,fn)=>{
fatherToSon.current[type] = fn
},[ component ])
const renderChildren = React.useMemo(() => {
return component ? React.cloneElement(component, { listenFather, sonSay }) : null
}, [component])
return layout ? React.createElement(layout, { fatherSay,listenSonSay, ...mergeProps, children: renderChildren }) : renderChildren
}
adopt
useRefSave the communication method .To write sonSay ( Child to parent component communication ),listenSonSay ( Parent and child components ),fatherSay( Parent to child component communication ),listenFather( The child listens to the parent component ) Method .
adopt cloneElement Clone inner layer components .
adopt createElement Create outer components .
2、 test demo
function GrandFather({ name, children }) {
return <div>
<p> {name} </p>
{children}
</div>
}
function Father({ children, listenSonSay, name ,fatherSay}) {
listenSonSay('sonSay', (message) => console.log(message))
return <div>
<p> {name} </p>
<button onClick={() => fatherSay('fatherSay','hello,son!')} >to Son</button>
{children}
</div>
}
function Son({ children, sonSay,listenFather ,name }) {
listenFather('fatherSay',(message) => console.log(message) )
return <div>
<p> {name} </p>
<button onClick={() => sonSay('sonSay', 'hello,father!')} >to Father</button>
{children || null}
</div>
}
export default function Index() {
return (
useComposeHooks(
useComposeHooks(
useComposeHooks(null,
Son, { name: 'Son' })
, Father, { name: 'Father' })
, GrandFather, { name: 'GrandFather' })
)
}
Above , We no longer need to do other processing to the business layer . Just call props The relevant methods inside are OK .
Next, let's look at the effect ( Non moving graph ):

Above , It's perfect . Through this case , Mainly to show you the custom hooks The combination mode is realized . Don't pay too much attention to the details of the code .

summary
Today, I talked about customization through a creative idea hooks Some other ways to play , Of course, in this article demo Just a case , It cannot be used in real business scenarios , Through this article, I hope you will have a good understanding of hooks Have a new understanding .

Previous recommendation
If you're going to design the network
Docker: Record the whole process from introduction to actual combat
Can programs run without an operating system ?
How to be in Kubernetes Pod Network packet capture in

Share

Point collection

A little bit of praise

Click to see
版权声明
本文为[CSDN cloud computing]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230044261056.html
边栏推荐
- L2-022 rearrange linked list (25 points) linked list operation
- BUUCTF 隐藏的钥匙
- flask项目跨域拦截处理以及dbm数据库学习【包头文创网站开发】
- Soft exam do not know how to choose subjects? This article answers your doubts
- C# WPF UI框架MahApps切换主题
- Leetcode 134. Station - service
- L2-035 完全二叉树的层序遍历 (25 分)
- 多测师杭州拱墅校区肖sir_高级金牌讲师_简历制作讲解
- L2-013 红色警报 (25 分)
- Nc13251 customer model
猜你喜欢

2.56 - try running show with different sample values_ Bytes code.

多测师杭州拱墅校区肖sir_高级金牌讲师_简历实战

C语言 #和 ##

群体智能协同作业与认知计算技术研究

你真的会用K折交叉吗? 对于K折交叉的思考

396. Rotation function / Sword finger offer II 013 Sum of two-dimensional submatrix

Symbolization of ArcGIS surface tin surface data

Beginner MCU lights up the first peripheral -- led light

MySQL -- table operation
![[image classification] understand Alex net](/img/a5/fb134430ae18fcc85c6746f5750b1d.jpg)
[image classification] understand Alex net
随机推荐
2.60 - suppose we number the bytes in a W-bit word from 0 (lowest bit) to w / 8 - 1 (highest bit). Write the code of the following C function, which will return an unsigned value, in which byte I of p
L2-012 关于堆的判断 (25 分)(字符串bug待解决)
SSM framework
Multi surveyor Xiao sir, Gongshu campus, Hangzhou_ Senior gold medal lecturer_ Resume practice
Information system project management - project initiation management
申请CA证书的步骤
BUUCTF 穿越时空的思念
C# 11 的这个新特性,我愿称之最强!
33岁,工作十年被裁员,所谓经验根本不值钱
Ifconfig how to get the statistics of network card
Binary search tree from preorder to preorder and postorder
What is the lifecycle of automated testing?
jsp 转换为thymeleaf格式的部分方式
thymeleaf common公共页面不能使用其他页面 (后台传入)相关的值(map,model等待注入的值)
2.57 - Programming show_ short, show_ Long and show_ Double, which print the byte representation of C language objects of types short, long and double respectively. Please try running on several machi
【图像分类】用最简单的代码复现SENet,初学者一定不要错过(pytorch)
L2-002 linked list weight removal (25 points)
Alternative scheme of 24V ~ 48V magnetic absorption track lamp fs2459 to mp2459
[image classification] reproduce senet with the shortest code. Xiaobai must be collected (keras, tensorflow2. X)
基于.NetCore开发博客项目 StarBlog - (2) 环境准备和创建项目