hooks使用的一些注意點


對於react hooks剛開始使用的開發者,為了保證不誤用,官方建議裝上eslint-plugin-react-hooks

npm install eslint-plugin-react-hooks

在.eslintrc.js文件里添加:

{
"plugins": [
"react-hooks"
],
"rules": {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn"
}
}

1.組件里有默認參數而且需要根據入參的變化而變化時使用函數 ()=>{} 傳參:

function App(props) {
  const [count, setCount] = useState(() => {
    return props.defaultCount || 0;
  })
}

2.useMemo(() => fn) 等價於 useCallback(fn)

const double = useMemo(() => {
  return count * 2;
}, [count === 3]);

const onClick = useCallback(() => {
  setClickCount(clickCount => clickCount + 1)
}, []);

3.useRef的兩種使用場景:

(1)相當於class component里的createRef

(2)想當於class component里的常量

const counterRef = useRef();
const onClick = useCallback(() => {
  counterRef.current.speak();
}, [counterRef]);
function useCount(defaultCount) {
  const [count, setCount] = useState(defaultCount) const it = useRef(); useEffect(() => { it.current = setInterval(() => { setCount(count => count + 1) }, 1000) }, []); useEffect(() => { if(count >= 10) { clearInterval(it.current); } }, []); return [count,setCount] }

4.函數作為參數傳遞時加useCallback

function useSize(){
  const [size, setSize] = useState({
    width: document.documentElement.clientWidth,
    height: document.documentElement.clientHeight
  });
  const onResize = useCallback(() => {
    setSize({
      width: document.documentElement.clientWidth,
      height: document.documentElement.clientHeight
    })
  }, []);
  useEffect(() => {
    window.addEventListener('resize', onResize, false);
    return () => {
      window.removeEventListener('resize', onResize, false);
    }
  }, [])
}

5.function component有了hooks的支持后有了類的功能

 (1)生命周期映射

useEffect(() => {
  //componentDidMount
  return () => {
  //componentWillUnmount
  }
}, [])

let renderCounter = useRef(0);
renderCounter.current++;

useEffect(() => {
  if(renderCounter > 1) {
    //componentDidUpdate
  }
})

(2)類成員映射

class App{
  it = 0;
}

function App() {
  const it = useRef(0)
}

(3)歷史props和state

function Counter() {
  const [count,setCount] = useState(0);
  const prevCountRef = useRef();
  useEffect(() => {
    prevCountref.current = count;
  })
  const prevCount = prevCountref.current;
  return <h1>Now: {count}, before: {prevCount}</h1>
}

(4)強制更新

  定義一個額外變量,讓函數依賴這個額外變量,這個額外變量變化時會執行更新

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM