浅谈hooks

浅谈hooks

Vue3和React16.8都已经支持了 hooks 作为组件编写的方式。

什么是hooks?

钩子编程是通过拦截软件模块间的函数调用、消息传递、事件传递来修改或扩展操作系统、应用程序或其他软件组件的行为的各种技术。处理被拦截的函数调用、事件、消息的代码,被称为钩子(hooks)。

React中的hooks

React只能在函数组件中使用hooks。

React中的hooks指的是以 use 开头的一系列方法,可以让我们避开class component写法,在函数式组件中完成全部的开发。

hooks函数以 use 开头是计算机中对于hooks约定俗成的写法。

Vue中的hooks

Vue只能在 setup 中使用hooks。

Vue中的hooks指的是以 use 开头的方法,他们提供了组件复用状态管理等能力,除此之外,Vue的组合式API也是一种hooks。

hooks的优点

  1. hooks可以将业务逻辑清晰划分解耦。
  2. hooks可复用性高、状态逻辑复用清晰,可以替代 mixin
  3. 避免了class组件需要频繁使用 bind 的麻烦。

React hooks实例

jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { useState, useEffect } from 'react'

const Demo = () => {
// 创建name状态和set方法
const [name, setName] = useState('')

// 处理副作用
useEffect(() => {
console.log(name)
},
[name]
)

// 依赖name动态计算message
const message = useMemo(() => {
return `my name is ${name}`
}, [name])

return (
<div> {message} </div>
)
}

export default Demo

Vue hooks实例

vue
1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<div>{{ message }}</div>
</template>

<script setup>
import { computed, ref } from 'vue'

const name = ref('')

const message = computed(() => {
return `my name is ${name.value}`
})
</script>

自定义hook

自定义hook是一种重用状态逻辑的方法。

下面以react hook为例,如何自定义一个hook:

  1. 给hook命名:以use开头。
  2. 编写函数:写一个普通的函数,函数内可以使用其他的hook。
  3. 使用写好的hook:在其他组件中可以使用编写好的hook,在组件中可以使用它返回的任何状态和函数。

自定义react hook实例:

jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { useState } from 'react'

// 自定义Hook:用于追踪和更新计数
function useCounter(initialCount) {
const [count, setCount] = useState(initialCount)

const increment = () => {
setCount(prevCount => prevCount + 1)
}

const decrement = () => {
setCount(prevCount => prevCount - 1)
}

return { count, increment, decrement }
}

// 在组件中使用自定义Hook
function CounterComponent() {
const { count, increment, decrement } = useCounter(0)

return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
)
}

export default CounterComponent

扩展阅读

  1. https://mp.weixin.qq.com/s/a1A7b6nzqNpZuv8KkN8nug

评论