useEffect当某些状态改变时,该钩子可以用来调用一个函数。如果将其
currentRange作为第二个参数传递到数组中,则仅在
currentRange更改时才调用该函数。
您还可以创建自己的自定义钩子,使用该
useRef钩子来跟踪效果是否是第一次运行,从而可以跳过第一次调用。
例
const { useRef, useState, useEffect } = React;function useEffectSkipFirst(fn, arr) { const isFirst = useRef(true); useEffect(() => { if (isFirst.current) { isFirst.current = false; return; } fn(); }, arr);}function App() { const [currentRange, setCurrentRange] = useState("24h"); useEffectSkipFirst( () => { console.log("hi"); }, [currentRange] ); return ( <button onClick={() => setCurrentRange(Math.floor(Math.random() * 24) + 1 + "h")} > Change range ({currentRange}) </button> );}ReactDOM.render(<App />, document.getElementById("root"));<script src="https://unpkg.com/react@16/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script><div id="root"></div>


