學習react hook的總結

react16推出了react hook,react hook使得functional組件擁有了class組件的一些特性,hook不能用在class 組件里。

React 中提供的 hooks:

  • useState:setState
  • useReducer:setState
  • useRef: ref
  • useContext: context,需配合 createContext 使用
  • useMemo: 可以對 setState 的優化
  • useEffect: 類似 componentDidMount/Update, componentWillUnmount,當效果為 componentDidMount/Update 時,總是在整個更新周期的最后(頁面渲染完成后)才執行
  • useLayoutEffect: 用法與 useEffect 相同,區別在于該方法的回調會在數據更新完成后,頁面渲染之前進行,該方法會阻礙頁面的渲染
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 有一個參數,該參數可傳如任意類型的值或者返回任意類型值的函數

useState 返回值為一個數組,數組的第一個參數為我們需要使用的 state,第二個參數為一個setter函數,可傳任意類型的變量,或者一個接收 state 舊值的函數,其返回值作為 state 新值。

useReducer

useReducer 接收三個參數,第一個參數為一個 reducer 函數第二個參數是reducer的初始值第三個參數為可選參數,值為一個函數,可以用來惰性提供初始狀態。這意味著我們可以使用使用一個 init 函數來計算初始狀態/值,而不是顯式的提供值。如果初始值可能會不一樣,這會很方便,最后會用計算的值來代替初始值。

reducer 接受兩個參數一個是 state 另一個是 action ,用法原理和 redux 中的 reducer 一致。

useReducer 返回一個數組,數組中包含一個 state 和 dispath,state 是返回狀態中的值,而 dispatch 是一個可以發布事件來更新 state 的函數。

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差不多只有輕微的執行順序上的不同先從useEffect說起吧

useEffect(func, array);

第一個參數為 effect 函數,該函數將在 componentDidMmount 時觸發和 componentDidUpdate 時有條件觸發(該添加為 useEffect 的第二個數組參數)。同時該 effect 函數可以返回一個函數(returnFunction),returnFunction 將會在 componentWillUnmount 時觸發在 componentDidUpdate 時先于 effect 有條件觸發(先執行 returnFuncton 再執行 effect,比如需要做定時器的清除)注意: 與 componentDidMount 和 componentDidUpdate 不同之處是,effect 函數觸發時間為在瀏覽器完成渲染之后。 如果需要在渲染之前觸發,需要使用 useLayoutEffect。

第二個參數 array 作為有條件觸發情況時的條件限制:

  • 如果不傳,則每次 componentDidUpdate 時都會先觸發 returnFunction(如果存在),再觸發 effect。
  • 如果為空數組[],componentDidUpdate 時不會觸發 returnFunction 和 effect。
  • 如果只需要在指定變量變更時觸發 returnFunction 和 effect,將該變量放入數組。
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創建的對象每次都返回一個相同的引用而createRef每次渲染都會返回一個新的引用

useMemo

在沒有hook時我們通常組件優化會用到pureComponent 之后又有為函數設計的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')
    // 只會根據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

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。