在函数组件内部完成setState更新后执行函数?



我想在功能组件setstate完成后执行一个函数。有两种方法可以用来判断状态更新是否已经完成

使用useEffect
  • use-state-with-callback(但是回调没有按预期调用)

我们可以使用useEffect来做一个正确的方法。但我们不能在所有情况下都使用。例如

const [count, setCount] = useState(0);
const func1 = ()=>{}
const func2 = ()=>{}
const func3 = ()=>{}

在func1和func3内部调用了setCount。在func1中的setCount之后,我需要调用func2,但不需要调用func3。如果我使用useEffect,每当count被更新时,func2就会被调用。

所以我需要一个适当的回调,需要在setState之后调用。

我可以在setState完成更新后执行函数吗?

对于功能组件,您需要从状态机的角度来考虑。当状态发生变化时调用组件函数,如果您想要执行呈现该状态的副作用,请使用useEffect。关键是要确保你的状态告诉你需要做什么。

听起来您需要第二个状态项来告诉您是否调用func2。大致:

function Example() {
const [count, setCount] = useState(0);
const [doTheCall, setDoTheCall] = useState(false);
const func1 = () => {
setCount((count) => {
const value = /*...*/;
setDoTheCall(true); // Indicate the call should be done
return value;
});
};
const func2 = () => {
// ...
}
const func3 = () => {
setCount(/*...*/);
};
useEffect(() => {
// Do the call if we're supposed to
if (doTheCall) {
func2();
setDoTheCall(false);
}
}, [doTheCall]);
// ...
}

这里我使用了一个简单的标志,但另一种方法是设置与count设置相同的值:

function Example() {
const [count, setCount] = useState(0);
const [countForCall, setCountForCall] = useState(false);
const func1 = () => {
setCount((count) => {
const value = /*...*/;
setCountForCall(value); // Set the value we compare with `count`
return value;
});
};
const func2 = () => {
// ...
}
const func3 = () => {
setCount(/*...*/);
};
useEffect(() => {
// Do the call if we're supposed to
if (count === countForCall) {
func2();
setCountForCall({}); // Will never match `count`
}
}, [count, countForCall]);
// ...
}

最新更新