Hook
Hook 的意义就是让函数组件也能使用 state,以及进行一些 state 的操作
State Hook
State Hook 在函数组件中的具体表现形式是通过使用 userState Hook
例如:
import React, { useState } from 'react'
function Example() {
// 此时相当于定义了一个state变量名为 count
// 定义了一个修改state的方法setCount
const [count, setCount] = useState(0)
return (
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
)
}
调用state
和 class 组件不同的是,在函数组件中调用state可以直接写函数名
例如使用 state 中的名为 count 的变量:
1.class 组件中:
{this.state.count}
2.函数组件中:
{count}
更新 state
1.class 组件中:
<p onClick={() => this.setState({count: this.state.count + 1})}></p>
2.函数组件中,则可以直接使用 useState 中定义的第二个参数,即是对应修改 state 的方法:
<p onClick={() => setCount(count + 1)}></p>
Effect Hook
Effect Hook 可以在函数组件中执行副作用操作
副作用操作
在React中,数据获取、设置订阅、手动更改 React 组件中的 DOM 都属于副作用操作。(即可以将 useEffect Hook 看作 componentDidMount、componentDidUpdate、componentWillUnMount三个生命周期函数的组成)
在 React 中两种常见副作用操作:需要清除和不需要清除的
无需清除的effect
例如在更新 DOM 之后运行一些额外的代码。例如发网络请求、手动变更 DOM 、记录日志等等
1.在 class 组件中的实现
一般把副作用操作放到 componentDidMount 和 componentDidUpdate 函数中
例如:
componentDidMount() {
console.log(111)
}
componentDidUpdate() {
console.log(111)
}
这两个生命周期函数实现的效果:会在组件挂载、和组件更新的时候会输出 111
2.在函数组件中的实现
useEffect(() => {
console.log(111)
})
useEffect() 会实现上面函数组件实现的效果,即 useEffect() 会在第一次渲染和每次更新后都会执行
需要清除的effect
例如订阅外部数据源这类的副作用就得清除
1.在class组件中实现(以React官网的例子举例)
一般会在 componentDidMount 中设置订阅,在componentWillUnmount 中清除它
假设有一个 ChatAPI 模块,它允许我们订阅好友的在线状态
componentDidMount() {
ChatAPI.subscribeToFirendStatus(
this.props.friend.id,
this.handleStatusChange
)
}
componentWillUnmount() {
ChatAPI.unsubscribeFromFirendStatus(
this.props.friend.id,
this.handleStatusChange
)
}
handleStatusChange(status) {
thsi.setState({
isOnline: status.isOnline
})
}
2.在函数组件中实现
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status, isOnline)
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(prosp.friend.id, handleStatusChange)
}
})
在这段代码中 useEffect() 方法中返回了一个清除函数,因为对 effect 来说,会有一个可选的清除机制,即 React 会在组件卸载的时候执行这个清除函数,同时也会对应上面的 React 在每次执行的时候 effect 都会执行。
![](https://i-blog.csdnimg.cn/blog_migrate/91e176e3a20f9cf25ef2530e0fa227c4.png)