在下面的代码中,当组件卸载时,会调用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);
}