react16推出了react hook,react hook使得functional組件擁有了class組件的一些特性阅酪,hook不能用在class 組件里。
React 中提供的 hooks:
- useState:setState
- useReducer:setState
- useRef: ref
- useContext: context芹助,需配合 createContext 使用
- useMemo: 可以對 setState 的優(yōu)化
- useEffect: 類似 componentDidMount/Update, componentWillUnmount也糊,當(dāng)效果為 componentDidMount/Update 時辫封,總是在整個更新周期的最后(頁面渲染完成后)才執(zhí)行
- useLayoutEffect: 用法與 useEffect 相同砖第,區(qū)別在于該方法的回調(diào)會在數(shù)據(jù)更新完成后荷腊,頁面渲染之前進(jìn)行,該方法會阻礙頁面的渲染
useState
function Counter({ initialCount }) {
const [count, setCount] = useState(0)
return (
<>
Count: {count}
<button onClick={() => setCount(0)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
</>
)
}
useState 有一個參數(shù)悄窃,該參數(shù)可傳如任意類型的值或者返回任意類型值的函數(shù)讥电。
useState 返回值為一個數(shù)組,數(shù)組的第一個參數(shù)為我們需要使用的 state轧抗,第二個參數(shù)為一個setter
函數(shù)恩敌,可傳任意類型的變量,或者一個接收 state 舊值的函數(shù)横媚,其返回值作為 state 新值纠炮。
useReducer
useReducer 接收三個參數(shù),第一個參數(shù)為一個 reducer 函數(shù)灯蝴,第二個參數(shù)是reducer的初始值恢口,第三個參數(shù)為可選參數(shù),值為一個函數(shù)穷躁,可以用來惰性提供初始狀態(tài)耕肩。這意味著我們可以使用使用一個 init
函數(shù)來計算初始狀態(tài)/值,而不是顯式的提供值问潭。如果初始值可能會不一樣猿诸,這會很方便,最后會用計算的值來代替初始值狡忙。
reducer 接受兩個參數(shù)一個是 state 另一個是 action 梳虽,用法原理和 redux 中的 reducer 一致。
useReducer 返回一個數(shù)組去枷,數(shù)組中包含一個 state 和 dispath怖辆,state 是返回狀態(tài)中的值,而 dispatch 是一個可以發(fā)布事件來更新 state 的函數(shù)删顶。
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}
<button
onClick={() => dispatch({type: 'reset', payload: initialCount})}>
Reset
</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</>
);
}
function render () {
ReactDOM.render(<Counter initialCount={0} />, document.getElementById('root'));
}
useEffect 和 useLayoutEffect
這個兩個hook差不多只有輕微的執(zhí)行順序上的不同先從useEffect
說起吧
useEffect(func, array);
第一個參數(shù)為 effect 函數(shù)竖螃,該函數(shù)將在 componentDidMmount 時觸發(fā)和 componentDidUpdate 時有條件觸發(fā)(該添加為 useEffect 的第二個數(shù)組參數(shù))。同時該 effect 函數(shù)可以返回一個函數(shù)(returnFunction)逗余,returnFunction 將會在 componentWillUnmount 時觸發(fā)和在 componentDidUpdate 時先于 effect 有條件觸發(fā)(先執(zhí)行 returnFuncton 再執(zhí)行 effect特咆,比如需要做定時器的清除)。 注意: 與 componentDidMount 和 componentDidUpdate 不同之處是录粱,effect 函數(shù)觸發(fā)時間為在瀏覽器完成渲染之后腻格。 如果需要在渲染之前觸發(fā),需要使用 useLayoutEffect啥繁。
第二個參數(shù) array 作為有條件觸發(fā)情況時的條件限制:
- 如果不傳菜职,則每次 componentDidUpdate 時都會先觸發(fā) returnFunction(如果存在),再觸發(fā) effect旗闽。
- 如果為空數(shù)組
[]
酬核,componentDidUpdate 時不會觸發(fā) returnFunction 和 effect蜜另。 - 如果只需要在指定變量變更時觸發(fā) returnFunction 和 effect,將該變量放入數(shù)組嫡意。
useContext
看名字就知道是react里context的hook
const Context = React.createContext('light');
// Provider
class Provider extends Component {
render() {
return (
<Context.Provider value={'dark'}>
<DeepTree />
</Context.Provider>
)
}
}
// Consumer
function Consumer(props) {
const context = useContext(Context)
return (
<div>
{context} // dark
</div>
)
}
useRef
import { React, useRef } from 'react'
const FocusInput = () => {
const inputElement = useRef()
const handleFocusInput = () => {
inputElement.current.focus()
}
return (
<>
<input type='text' ref={inputElement} />
<button onClick={handleFocusInput}>Focus Input</button>
</>
)
}
export default FocusInput
與createRef比 举瑰,useRef創(chuàng)建的對象每次都返回一個相同的引用而createRef每次渲染都會返回一個新的引用
useMemo
在沒有hook時我們通常組件優(yōu)化會用到pureComponent 之后又有為函數(shù)設(shè)計的memo方法,通過策略來判斷是否更新蔬螟。
// 使用useMemo
import React, { useState,useMemo, memo } from 'react'
const Child = memo(({ config }) => {
console.log(config)
return <div style={{ color:config.color }}>{config.text}</div>
})
function MemoCount() {
const [count, setCount] = useState(0)
const [color, setColor] = useState('blue')
// 只會根據(jù)color的改變來返回不同的對象此迅,否則都會返回同一個引用對象
const config = useMemo(()=>({
color,
text:color
}),[color])
return (
<div>
<button
onClick={() => {
setCount(count + 1)
}}
>
Update Count
</button>
<button
onClick={() => {
setColor('green')
}}
>
Update Color
</button>
<div>{count}</div>
<Child config={config} />
</div>
)
}
export default MemoCount