我正在使用 React Router,并且有两条渲染相同组件的路由:
<Switch>
<Route path="/aaa" component={Cmp} />
<Route path="/bbb" component={Cmp} />
</Switch>
这是 Cmp 实现:
class Cmp extends Component {
componentWillUnmount() {
console.log('******************* UNMOUNTED');
}
render() {
return null;
}
}
正如我所料,在 /aaa
和 /bbb
之间导航不会卸载 Cmp。
我正在转向钩子(Hook),所以我重写了组件:
function Cmp() {
useEffect(() => {
return () => {
console.log('******************* UNMOUNTED');
};
});
return null;
}
非常令人惊讶的是,运行应用程序时,在 /aaa
和 /bbb
console.log 之间导航,发现 Cmp 已卸载。
知道如何使用函数组件和钩子(Hook)来防止不必要的卸载安装吗?
最佳答案
If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works. ...read more
现在,每次重新渲染 Cmp
组件时都会调用您的效果。如果您只想在卸载时调用效果,则必须将带有空数组的第二个参数传递给 useEffect
:
useEffect(() => {
return () => {
console.log('******************* UNMOUNTED');
};
}, []);
关于reactjs - React router 卸载功能组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56150069/