react-hooks:跳过使用中的第一次运行

时间:2018-11-17 13:04:14

标签: reactjs react-hooks

如何跳过useEffect钩中的第一次运行。

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

1 个答案:

答案 0 :(得分:10)

useRef hook can be used to store any mutable value,因此您可以存储一个布尔值,指示是否是第一次运行效果。

示例

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/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>