[英]How to know if its the props that changed or the inner state in useEffect
I have a component with inner state that I want to update its initial state using props so I have to watch the props too.我有一个具有内部状态的组件,我想使用 props 更新其初始状态,因此我也必须观看 props。 however I'd like to know when its the props that changed so that I run the function related to it once and keep it away from the inner component state.\\
但是我想知道它的 props 何时发生变化,以便我运行一次与其相关的函数并使其远离内部组件状态。\\
This is because I am unable to properly update the inner state as that thing will always run everytime the useEffect triggers这是因为我无法正确更新内部状态,因为每次 useEffect 触发时它都会运行
the following useEffect is for a Modal that I am setting visible or not from the parent component state(so its always mounted).以下 useEffect 适用于我设置的从父组件状态可见或不可见的模态(因此它始终安装)。
useEffect(() => {
// I want to run the following once
if (Object.getOwnPropertyNames(propState).length !== 0) {
console.log(propState);
setState(()=> {
innerState = propState.user_name
});
}
}, [propState, innerState]);
You can check value in inner state and propState.您可以检查内部状态和 propState 中的值。 If they equal, when skip setState.
如果它们相等,则跳过 setState。
useEffect(() => {
if (propState?.user_name && propState !== innerState.user_name) {
setState(()=> {
innerState = propState.user_name
});
}
}, [propState, innerState]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.