【发布时间】:2020-04-03 09:09:39
【问题描述】:
专家, 请解释一下,为什么在下面的代码中,属性的状态不会在 useEffect 清理函数中被清理?
我的组件:
export default function TestComp() {
let { id } = useParams();
const [value, setValue] = useState(null);
console.log('[TestComp] called...');
const cleanup = () => {
console.log('[TestComp] old value', value);
setValue(null);
};
useEffect(() => {
console.log('[TestComp] id changed: ', id);
console.log('[TestComp] value in useEffect', value);
setValue(id);
return () => {
cleanup();
}
}, [id]);
return (<React.Fragment>Test id: {id}</React.Fragment>)
}
控制台输出:
[TestComp] called... TestComp.js:8
[TestComp] old value satellites:MTP TestComp.js:11
[TestComp] id changed: satellites:MTP TestComp.js:16
[TestComp] value in useEffect satellites:FPGA TestComp.js:17
[TestComp] called... 2 TestComp.js:8
[TestComp] old value satellites:FPGA TestComp.js:11
[TestComp] id changed: satellites:FNE TestComp.js:16
[TestComp] value in useEffect satellites:MTP TestComp.js:17
[TestComp] called... TestComp.js:8
我希望,在第二次调用 useEffect 时,value 将被清理并为 null,但它仍保留旧值:
value in useEffect satellites:MTP TestComp.js:17
提前谢谢你。
【问题讨论】:
-
它会在你的组件卸载时清理你的状态。基本上如果你想实现componentWillUnmount。比你必须在 useEffect 中返回。更多参考请看这篇文章:daveceddia.com/useeffect-hook-examples
-
尝试将日志移动到另一个
useEffect并以value作为依赖项
标签: reactjs state use-effect