[英]How to run a single useEffect both on re-render and on dependency change?
I have the following code,我有以下代码,
const [over, setOver] = useState(false); useEffect(() => { //some logic }, [over]);
and I want to be able to run the use effect when the (over) has been changed and also if component props changes as for now the code runs only when over has been changed, similar to并且我希望能够在 (over) 被更改时运行使用效果,并且如果组件道具现在更改,代码仅在 over 被更改时运行,类似于
useEffect(() => { //some logic }, []);
Your first code and second are not similar at all.您的第一个代码和第二个代码根本不相似。 Second one runs once only when the component is mounted (added to the DOM).第二个仅在安装组件(添加到 DOM)时运行一次。 And first code will run onComponentMount and onOverChange .第一个代码将运行onComponentMount和onOverChange 。
You need to understand react component lifecycle to understand how useEffect works.您需要了解 React 组件生命周期才能了解useEffect 的工作原理。
There are 3 lifecycle events.有 3 个生命周期事件。 onMount , onStateChange and onUnMount . onMount 、 onStateChange和onUnMount 。 The callback function runs when onMount or onStateChange is triggered.回调 function 在onMount或onStateChange被触发时运行。 When you use []
it means the code will only run when mounted and not on any stateChange event.当您使用[]
时,这意味着代码只会在挂载时运行,而不是在任何 stateChange 事件上运行。 (Cause there isn't any state available to watch) (因为没有任何 state 可供观看)
useEffect(() => {
// this will run when component is added to the DOM or a dependency state have changed
console.log("mounted or dependency state changed");
// this will run when component is destroyed
return () => console.log("component unmounted");
}, [dependency1, dependency2]);
One straightforward way to do this is add the props in dependency array一种直接的方法是在依赖数组中添加道具
useEffect(() => {
//some logic
}, [over,props]);
But that is not really a good idea但这并不是一个好主意
Go through this once You might not need an effect Go 通过这一次你可能不需要效果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.