React hooks使用方法全面匯總
1. 前言
react16.8推出hooks更好的支持函數組件,使用函數組件更容易進行代碼的復用,拓展性更強。
2. useState
useState類似于class組件的state功能,用于更新視圖
import React, { Component, useState } from 'react'; export default function Hello() { const [count, setCount] = useState(0); //設置默認值為0 return <div> {count} <button onClick={()=>setCount(count + 1)}>增加</button> </div> } //useState還可以使用函數進行賦值 const [count, setCount] = useState(()=>0); //設置默認值為0
3. useEffect
useEffect接受兩個參數,第一個參數是要執(zhí)行的回調函數,第二個參數是依賴的參數,如下面的例子里只有當count發(fā)生變化的時候才會打印count,當第二個參數為空數組的時候,組件在渲染完成后會執(zhí)行一次,第二個參數不傳遞的時候每次渲染都會執(zhí)行
export default function Hello() { const [count, setCount] = useState(() => 0); //設置默認值為0 // useEffect useEffect(() => { }, [count]) return <div> {count} <button onClick={() => setCount(count + 1)}>增加</button> </div> }
帶有返回值的useEffect用于清除執(zhí)行過程中的副作用
useEffect(()=>{ const timer = setInterval(() => { console.log(count); }, 1000); window.addEventListener('resize',handleResize); return function(){ clearInterval(timer); window.removeEventListener('resize',handleResize); } }, [count])
如果每次執(zhí)行useEffect都定義一個定時器,那定時器會越來越多,通過在返回函數中清除定時器取消這個副作用。useEffect返回函數的執(zhí)行時機是下一次useEffect執(zhí)行之前。
利用這一點可以實現防抖和節(jié)流函數
4. useLayoutEffect
dom渲染之前的useEffect: useLayoutEffect =》 dom渲染 =》useLayout
export default function Hello (props){ const [count, setCount] = useState(0); useEffect(()=>{ console.log('useEffect'); },[count]); useLayoutEffect(()=>{ console.log('useLayoutEffect'); },[count]) return <div> {count} <button onClick={()=> setCount(count+1)}>增加</button>; </div> }
使用useEffect和useLayoutEffect去更新視圖狀態(tài)會產生不同的效果,useEffect會有一個狀態(tài)到另一個狀態(tài)的過程(閃動效果),useLayoutEffect直接渲染最終狀態(tài)
5. useMemo
useMemo的作用就是緩存,減少代碼的執(zhí)行次數。
下面的代碼點擊按鈕count狀態(tài)發(fā)生變化,整個Hello函數體內的代碼都會執(zhí)行,每次點擊按鈕都會打印str的值
export default function Hello (props){ const [count, setCount] = useState(0); const [str, setStr] = useState('hello hooks!'); useEffect(()=>{ console.log('useEffect'); },[count]); console.log('str'); //每次渲染都會執(zhí)行 return <div> {count} {str} <button onClick={()=> setCount(count+1)}>增加</button> </div> }
使用useMemeo進行緩存,當str發(fā)生變化的時候再執(zhí)行打印語句
useMemo(()=>{ console.log(str); },[str])
useMemo還可以用來緩存函數
export default function Hello (props){ const [count, setCount] = useState(0); const [str, setStr] = useState('hello hooks!'); useEffect(()=>{ console.log('useEffect'); },[count]); // 使用useMemo緩存函數 const hanldeClick = useMemo(()=>{ return function(){ console.log(count); }; },[count]); return <div> {count} {str} <button onClick={()=> setCount(count+1)}>增加</button> <button onClick={hanldeClick}>測試</button> </div> }
6. useCallback
useCallback的功能是緩存函數,取的是useMemo的運行結果
const handleClick = useMemo(()=>{ return function(){ console.log(count); }; },[count]); const handleClick = useCallback(()=>{ console.log(count); },[count])
上面兩個實現的功能是一樣的,在平時的開發(fā)中要盡量使用useMemo去緩存函數
7. useRef
- 獲取元素dom ref.current
- 緩存數據
使用useRef獲取元素
export default function Hello(props) { const ref = useRef(null); useEffect(() => { console.log(ref.current); // <input id='input'> }) return <div> <input ref={ref} id="input" /> </div> }
使用useRef保存數據,當ref.current發(fā)生變化的時候視圖不會重新渲染
export default function Hello(props) { const ref = useRef(null); useEffect(() => { ref.current = 'hello hooks!'; }); return <div> <span> {ref.current}</span> </div> }
8. useReducer
useReducer用于更新復雜的state提升渲染性能,使用方法與redux類似。與redux的區(qū)別是redux管理的是全局的數據做數據共享,useReducer是useState的替代方案,只管理單個組件的狀態(tài)。
onst reducer = (state, action) => { switch (action.name) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: return state; } }; const initState = { count: 0 }; export default function Hello() { const [state, dispatch] = useReducer(reducer, initState) return <div> <span> {state.count}</span> <button onClick={() => dispatch({ name: 'increment' })}>增加</button> <button onClick={() => dispatch({ name: 'decrement' })}>減少</button> </div> }
9. useContext
useContext用來解決props層層傳遞,嵌套很深的問題。
export default function Father() { const [count, setCount] = useState(0); const handleClick = useCallback(() => { setCount(count + 1); }, [count]); return <div> {count} <button onClick={() => handleClick()}>增加</button> <MyContext.Provider value={{ count }}> <Children /> </MyContext.Provider> </div> }; function Children() { const context = useContext(MyContext); return <div> 父組件的count: {context.count} </div> };
10. memo
在calss組件中通過對比props,子組件接收的props發(fā)生變化的時候才進行更新渲染,在函數組件中沒有識別props的能力,當父組件重新渲染的時候子組件也會重新渲染,在使用memo包裹后只有props發(fā)生變化的時候才會重新渲染。memo的功能類似于calss組件對pureComponent對props進行了淺比較。
export default function Father() { const [count, setCount] = useState(0); const [str, setStr] = useState('hello hooks!'); return <div> {count} {str} <button onClick={() => setCount(count + 1)}>增加count</button> <button onClick={() => setStr(str + 1)}>修改str</button> <Children count={count} /> </div> }; const Children = React.memo(function Children(props) { console.log('子組件渲染'); return <div> 子組件: {props.count} </div> } );
上面的例子中,count變化的時候子組件渲染更新,str變化的時候子組件不重新渲染。
到此這篇關于React hooks使用方法全面匯總的文章就介紹到這了,更多相關React hooks內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Create?react?app修改webapck配置導入文件alias
這篇文章主要為大家介紹了Create?react?app修改webapck配置導入文件alias,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12React.js入門實例教程之創(chuàng)建hello world 的5種方式
React 是近期非常熱門的一個前端開發(fā)框架。應用非常廣泛,接下來通過本文給大家介紹React.js入門實例教程之創(chuàng)建hello world 的5種方式 ,需要的朋友參考下吧2016-05-05