新聞中心
簡介
只能在函數(shù)組件的頂級作用域使用;只能在函數(shù)組件或者其他 Hooks 中使用。

hooks 使用時必須確保:
- 所有 Hook 必須要被執(zhí)行到。
- 必須按順序執(zhí)行。
ESlint
使用 Hooks 的一些特性和要遵循某些規(guī)則。
React 官方提供了一個 ESlint 插件,專門用來檢查 Hooks 是否正確被使用。
安裝插件:
npm install eslint-plugin-react-hooks --save-dev
在 ESLint 配置文件中加入兩個規(guī)則:rules-of-hooks 和 exhaustive-deps。
{
"plugins": [
// ...
"react-hooks"
],
"rules": {
// ...
// 檢查 Hooks 的使用規(guī)則
"react-hooks/rules-of-hooks": "error",
// 檢查依賴項的聲明
"react-hooks/exhaustive-deps": "warn"
}
}
useState
import React, { userState } from 'react'
function Example() {
// 聲明一個叫count的state變量,初始值為0
// 可以使用setCount改變這個count
const [ count, setCount ] = useState(0)
return (
You clicked {count} times
);
}
useState 的入?yún)⒁部梢允且粋€函數(shù)。當(dāng)入?yún)⑹且粋€函數(shù)的時候,這個函數(shù)只會在這個組件初始化渲染的時候執(zhí)行。
const [ count, setCount ] = useState(() => {
const initialCount = someExpensiveComputation(props)
return initialCount
})
setState 也可以接收一個函數(shù)作為參數(shù): setSomeState(prevState => {})。
// 常見寫法
const handleIncrement = useCallback(() => setCount(count + 1), [count])
// 下面這種性能更好些
// 不會每次在 count 變化時都使用新的。
// 從而接收這個函數(shù)的組件 props 就認(rèn)為沒有變化,避免可能的性能問題
const handleIncrement = useCallback(() => setCount(q => q + 1), [])
useEffect
useEffect 會在每次 DOM 渲染后執(zhí)行,不會阻塞頁面渲染。
在頁面更新后才會執(zhí)行。即:每次組件 render 后,判斷依賴并執(zhí)行。
它同時具備 componentDidMount 、 componentDidUpdate 和 componentWillUnmount 三個生命周期函數(shù)的執(zhí)行時機。
useEffect 共兩個參數(shù): callback 和 dependences 。規(guī)則如下:
- dependences 不存在時,默認(rèn)是所有的 state 和 props 。即:每次 render 之后都會執(zhí)行 callback。
- dependences 存在時, dependences 數(shù)組中的所有項,只要任何一個有改變,在觸發(fā) componentDidUpdate 之后也會執(zhí)行 callback。
- dependences 為空數(shù)組時,表示不依賴任何的 state 和 props 。即: useEffect 只會在 componentDidMount 之后執(zhí)行一次。其后 state 或 props 觸發(fā)的 componentDidUpdate 后不會執(zhí)行 callback。
- callback 可以有返回值。該返回值是一個函數(shù)。會在 componentWillUnmount 時自動觸發(fā)執(zhí)行。
依賴項中定義的變量一定是會在回調(diào)函數(shù)中用到的,否則聲明依賴項其實是沒有意義的。
依賴項一般是一個常量數(shù)組,而不是一個變量。因為一般在創(chuàng)建 callback 的時候,你其實非常清楚其中要用到哪些依賴項了。
React 會使用淺比較來對比依賴項是否發(fā)生了變化,所以要特別注意數(shù)組或者對象類型。
如果你是每次創(chuàng)建一個新對象,即使和之前的值是等價的,也會被認(rèn)為是依賴項發(fā)生了變化。這是一個剛開始使用 Hooks 時很容易導(dǎo)致 Bug 的地方。
在頁面更新之后會觸發(fā)這個方法 :
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
You clicked {count} times
);
}
如果想針對某一個數(shù)據(jù)的改變才調(diào)用這個方法,需要在后面指定一個數(shù)組,數(shù)組里面是需要更新的那個值,它變了就會觸發(fā)這個方法。數(shù)組可以傳多個值,一般會將 Effect 用到的所有 props 和 state 都傳進去。
// class 組件做法
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
document.title = `You clicked ${this.state.count} times`
}
}
// 函數(shù)組件 hooks做法:只有 count 變化了才會打印出 aaa
userEffect(() => {
document.title = `You clicked ${count} times`
}, [count])
如果我們想只在 mounted 的時候觸發(fā)一次,那我們需要指定后面的為空數(shù)組,那么就只會觸發(fā)一次,適合我們做 ajax 請求。
userEffect(() => {
console.log('mounted')
}, [])
如果想在組件銷毀之前執(zhí)行,那么我們就需要在 useEffect 里 return 一個函數(shù)。
useEffect(() => {
console.log("mounted");
return () => {
console.log('unmounted')
}
}, []);
示例:在 componentDidMount 中訂閱某個功能,在 componentWillUnmount 中取消訂閱。
// class組件寫法
class Test extends React.Component {
constructor(props) {
super(props)
this.state = { isOnline: null }
this.handleStatusChange = this.handleStatusChange.bind(this)
}
componentDidMount() {
ChatApi.subscribeToFriendStatus(
this.props.friend.id,
this.handleStatusChange
)
}
componentWillUnmount() {
ChatApi.unsubscribeFromFriendStatus(
this.props.friend.id,
this.handleStatusChange
)
}
handleStatusChange(status) {
this.setState({
isOnline: status.isOnline
})
}
render() {
if (this.state.isOnline === null) {
return 'loading...'
}
return this.state.isOnline ? 'Online' : 'Offline'
}
}
// 函數(shù)組件 hooks寫法
function Test1(props) {
const [ isOnline, setIsOnline ] = useState(null)
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline)
}
ChatApi.subscribeToFriendStatus(props.friend.id, handleStatusChange)
// 返回一個函數(shù)來進行額外的清理工作
return function cleanup() {
ChatApi.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange)
}
})
if (isOnline === null) {
return 'loading...'
}
return isOnline ? 'Online' : 'Offline'
}
useLayoutEffect
useLayoutEffect 的用法跟 useEffect 的用法是完全一樣的,它們之間的唯一區(qū)別就是執(zhí)行的時機。
useLayoutEffect 會阻塞頁面的渲染。會保證在頁面渲染前執(zhí)行,也就是說頁面渲染出來的是最終的結(jié)果。
如果使用 useEffect ,頁面很可能因為渲染了2次而出現(xiàn)抖動。
絕大多數(shù)情況下,使用 useEffect 即可。
useContext
useContext 可以很方便的去訂閱 context 的改變,并在合適的時候重新渲染組件。
接收一個 context 對象(React.createContext 的返回值)并返回該 context 的當(dāng)前值。
context 基本示例:
// 因為祖先組件和子孫組件都用到這個ThemeContext,
// 可以將其放在一個單獨的js文件中,方便不同的組件引入
const ThemeContext = React.createContext('light')
class App extends React.Component {
render() {
return (
)
}
}
// 中間層組件
function Toolbar(props) {
return (
)
}
class ThemedButton extends React.Component {
// 通過定義靜態(tài)屬性 contextType 來訂閱
static contextType = ThemeContext
render() {
return
}
}
針對函數(shù)組件的訂閱方式:
function ThemedButton() {
// 通過定義 Consumer 來訂閱
return (
{ value => }
)
}
使用 useContext 來訂閱:
function ThemedButton() {
const value = useContext(ThemeContext)
return
}
在需要訂閱多個 context 的時候,對比:
// 傳統(tǒng)的實現(xiàn)方法
function HeaderBar() {
return (
{user =>
{notification =>
Welcome back, {user.name}!
You have {notifications.length} notifications.
}
}
)
}
// 使用 useContext
function HeaderBar() {
const user = useContext(CurrentUser)
const notifications = useContext(Notifications)
return (
Welcome back, {use.name}!
You have {notifications.length} notifications.
)
}
useReducer
useReducer 用法跟 Redux 非常相似,當(dāng) state 的計算邏輯比較復(fù)雜又或者需要根據(jù)以前的值來計算時,使用這種 Hook 比 useState 會更好。
function init(initialCount) {
return { count: initialCount }
}
function reducer(state, action) {
switch(action.type) {
case 'increment':
return { count: state.count + 1 }
case 'decrement':
return { count: state.count - 1 }
case 'reset':
return init(action.payload)
default:
throw new Error()
}
}
function Counter({ initialCount }) {
const [state, dispatch] = useReducer(reducer, initialCount, init)
return (
<>
Count: {state.count}
>
)
}
結(jié)合 context API,我們可以模擬 Redux 的操作:
const TodosDispatch = React.createContext(null)
const TodosState = React.createContext(null)
function TodosApp() {
const [todos, dispatch] = useReducer(todosReducer)
return (
)
}
function DeepChild(props) {
const dispatch = useContext(TodosDispatch)
const todos = useContext(TodosState)
function handleClick() {
dispatch({ type: 'add', text: 'hello' })
}
return (
<>
{todos}
>
)
}
useCallback / useMemo / React.memo
- useCallback 和 useMemo 設(shè)計的初衷是用來做性能優(yōu)化的。
- useCallback 緩存的是方法的引用。
- useMemo 緩存的則是方法的返回值。
- 使用場景是減少不必要的子組件渲染。
// useCallback
function Foo() {
const [ count, setCount ] = useState(0)
const memoizedHandleClick = useCallback(
() => console.log(`Click happened with dependency: ${count}`), [count],
)
return
}
// useMemo
function Parent({a, b}) {
// 當(dāng) a 改變時才會重新渲染
const child1 = useMemo(() =>, [a])
// 當(dāng) b 改變時才會重新渲染
const child2 = useMemo(() =>, [b])
return (
<>
{child1}
{child2}
>
)
}
若要實現(xiàn) class 組件的 shouldComponentUpdate 方法,可以使用 React.memo 方法。
區(qū)別是它只能比較 props ,不會比較 state。
const Parent = React.memo(({ a, b}) => {
// 當(dāng) a 改變時才會重新渲染
const child1 = useMemo(() => , [a])
// 當(dāng) b 改變時才會重新渲染
const child2 = useMemo(() => , [b])
return (
<>
{child1}
{child2}
>
)
})
return
// class組件獲取ref
class Test extends React.Component {
constructor(props) {
super(props)
this.myRef = React.createRef()
}
componentDidMount() {
this.myRef.current.focus()
}
render() {
return
}
}
// 使用useRef
function Test() {
const myRef = useRef(null)
useEffect(() => {
myRef.current.focus()
}, [])
return
}
useRef 值的變化不會引起組件重繪,可以存一些跟界面顯示無關(guān)的變量。
函數(shù)式組件不能設(shè)置 ref ,想保存其中的某些值,可以通過 React.forwardRef。
import React, { useState, useEffect, useRef, forwardRef } from 'react'
export default function Home(props) {
const testRef = useRef(null)
useEffect(() => {
console.log(testRef.current)
}, [])
return (
我們都是中國人
)
}
/* eslint-disable react/display-name */
// const Test = forwardRef((props, ref) => (
//
// test module
// {props.children}
//
// ))
const Test = forwardRef(function Test(props, ref) {
const [count, setCount] = useState(1)
useEffect(() => {
ref.current = {
count,
setCount
}
})
return (
當(dāng)前count:{count}
)
})
自定義hook
自定義 Hook 是一個函數(shù),但是名稱必須是以 use 開頭,函數(shù)內(nèi)部可以調(diào)用其他的 Hook。
自定義 Hook 是一種自然遵循 Hook 設(shè)計的約定,而并不是 React 的特性。
跟普通的 hook 一樣,只能在函數(shù)組件或者其他 Hooks 中使用。
文章名稱:一篇帶給你ReactHooks完全上手指南
路徑分享:http://www.dlmjj.cn/article/djehcsh.html


咨詢
建站咨詢
