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

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

useEffect(() => {

const first = // ???

if (first) {

// skip

} else {

// run main code

}

}, [id]);

回答:

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

以上是 react-hooks:跳过第一次在useEffect中运行 的全部内容, 来源链接: utcz.com/qa/435820.html

回到顶部