小编典典

react-hooks:跳过第一次在useEffect中运行

reactjs

我该如何跳过第一次遇到问题useEffect

useEffect(() => {
    const first = // ???
  if (first) {
    // skip
  } else {
    // run main code
  }
}, [id]);

阅读 2589

收藏
2020-07-22

共1个答案

小编典典

useRef挂钩可用于存储任何可变值,因此您可以存储一个布尔值,指示是否是第一次运行效果。

const { useState, useRef, useEffect } = React;



function MyComponent() {

  const [count, setCount] = useState(0);



  const isFirstRun = useRef(true);

  useEffect (() => {

    if (isFirstRun.current) {

      isFirstRun.current = false;

      return;

    }



    console.log("Effect was run");

  });



  return (

    <div>

      <p>Clicked {count} times</p>

      <button

        onClick={() => {

          setCount(count + 1);

        }}

      >

        Click Me

      </button>

    </div>

  );

}



ReactDOM.render(

  <MyComponent/>,

  document.getElementById("app")

);


<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>

<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>



<div id="app"></div>
2020-07-22