【发布时间】:2019-10-02 15:22:40
【问题描述】:
我正在使用 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。
我正在转向钩子,所以我重写了组件:
function Cmp() {
useEffect(() => {
return () => {
console.log('******************* UNMOUNTED');
};
});
return null;
}
非常令人惊讶的是,在运行应用程序时,在 /aaa 和 /bbb console.log 之间导航 Cmp 已卸载。
知道如何使用函数组件和钩子来防止不必要的卸载吗?
【问题讨论】:
-
看看这个,它可能会帮助reactjs.org/docs/…
-
不确定这是否有帮助,但看看React.memo
标签: reactjs react-router react-router-v4 react-hooks