react-hooks:跳过 useEffect 中的第一次运行 [英] react-hooks: skip first run in useEffect
本文介绍了react-hooks:跳过 useEffect 中的第一次运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 useEffect
钩子中跳过第一次运行.
useEffect(() => {常量第一 =//???如果(第一){//跳过} 别的 {//运行主代码}}, [ID]);
解决方案
useRef
钩子可用于存储任何可变值,因此您可以存储一个布尔值,指示是否是第一次运行效果.
示例
const { useState, useRef, useEffect } = React;函数 MyComponent() {const [count, setCount] = useState(0);const isFirstRun = useRef(true);useEffect(() => {如果(isFirstRun.current){isFirstRun.current = false;返回;}console.log("效果已运行");});返回 (<div><p>点击了 {count} 次</p><按钮onClick={() =>{设置计数(计数 + 1);}}>点击我按钮>
);}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>
How I can skip first run in useEffect
hook.
useEffect(() => {
const first = // ???
if (first) {
// skip
} else {
// run main code
}
}, [id]);
解决方案
The useRef
hook can be used to store any mutable value, so you could store a boolean indicating if it's the first time the effect is being run.
Example
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 中的第一次运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文