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、componentWillMount三個生命週期函數的組成)
在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都會執行。