我们可以使用该
useRef钩子来存储我们喜欢的任何可变值,因此我们可以使用它来跟踪
useEffect函数是否是第一次运行。
如果我们希望效果在与该效果相同的阶段中运行
componentDidUpdate,则可以使用
useLayoutEffect。
例
const { useState, useRef, useLayoutEffect } = React;function ComponentDidUpdateFunction() { const [count, setCount] = useState(0); const firstUpdate = useRef(true); useLayoutEffect(() => { if (firstUpdate.current) { firstUpdate.current = false; return; } console.log("componentDidUpdateFunction"); }); return ( <div> <p>componentDidUpdateFunction: {count} times</p> <button onClick={() => { setCount(count + 1); }} > Click Me </button> </div> );}ReactDOM.render( <ComponentDidUpdateFunction />, document.getElementById("app"));<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script><div id="app"></div>


