Update-useEffect在没有调用函数的情况下在重新发布程序中返回了函数



在下面的代码中,当组件卸载时,会调用useEffect内部的返回函数。

function MyComponent() {
const [variable, setVariable] = useState(1)

useEffect(() => {
return () => console.log(variable);
}, []);
setVariable(2);
}

但我希望与上面的代码有所不同:我希望在变量值更改时更新返回函数的定义,而不调用它(卸载时除外(。我该怎么办?

您应该将variable设置为useEffect:的依赖项

function MyComponent() {
const [variable, setVariable] = useState(1)

useEffect(() => {
return () => console.log(variable);
}, [variable]);
setVariable(2);
}

因此,每当variable发生变化时,console.log就会运行。

您可以尝试这种方式

function MyComponent() {
const [variable, setVariable] = useState(1)
const [unmountingFunction, setUnmountingFunction] = useState(() => console.log(variable))
//whenever you update value, this unmounting function will be updated too
useEffect(() => {
setUnmountingFunction(() => console.log("Your unmounting function is here"))
}, [variable]);

useEffect(() => {
return unmountingFunction;
}, []);
setVariable(2);
}

最新更新