react-hooks:先跳过 运行 in useEffect
react-hooks: skip first run in useEffect
如何在 useEffect
挂钩中先跳过 运行。
useEffect(() => {
const first = // ???
if (first) {
// skip
} else {
// run main code
}
}, [id]);
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>
如何在 useEffect
挂钩中先跳过 运行。
useEffect(() => {
const first = // ???
if (first) {
// skip
} else {
// run main code
}
}, [id]);
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>