最佳答案
如何使用 useEffect
钩子(或任何其他钩子)来复制 componentWillUnmount
?
在传统的 class 组件中,我会这样做:
class Effect extends React.PureComponent {
componentDidMount() { console.log("MOUNT", this.props); }
componentWillUnmount() { console.log("UNMOUNT", this.props); }
render() { return null; }
}
与 useEffect
挂钩:
function Effect(props) {
React.useEffect(() => {
console.log("MOUNT", props);
return () => console.log("UNMOUNT", props)
}, []);
return null;
}
(完整例子: https://codesandbox.io/s/2oo7zqzx1n)
这是不工作的,因为“清理”函数返回在 useEffect
捕获道具,因为他们在挂载期间,而不是状态的道具在卸载。
我怎样才能得到最新版本的道具在 useEffect
清理 没有运行的功能体(或清理)对每个道具的变化?
类似的 有个问题没有解决访问最新道具的问题。
反应文件州:
如果您想运行一个效果并且只清除一次(在挂载和卸载时) ,那么可以传递一个空数组([])作为第二个参数。这告诉 React,您的效果不依赖于任何来自道具或状态的值,因此它永远不需要重新运行。
不过在这种情况下,我依靠的道具... ... 但只有清理的一部分..。