【发布时间】:2020-08-01 09:07:39
【问题描述】:
我会先说一切正常,只是我试图了解到底发生了什么以及为什么我会看到这种行为。
假设我有一个组件FooComponent,以及两个不同的路由/foo 和/bar。我将它们渲染如下:
<Route
exact
path="/foo"
render={({ location }) => <FooComponent location={location} />}
/>
<Route
path="/bar"
render={({ location }) => <FooComponent location={location} />}
/>
在页面/foo 和/bar 之间单击时,FooComponent 似乎只安装一次。为了测试这一点,下面是 FooComponent 的实现方式:
const FooComponent = ({ location }) => {
useEffect(() => {
console.log("Mount");
return () => {
console.log("Cleanup");
};
}, []);
return <div>At {location.pathname}</div>;
};
Mount 只记录一次。
这完全让我感到困惑,因为 FooComponent 是由两个完全不同的父 Route 组件渲染的,我认为 React 只会对使用不同子元素重新渲染的同一个父组件执行协调。此外,将其中一个更改为返回 <div><FooComponent location={location} /></div> 并保留另一个原样会导致组件卸载。
Here 是可重现的示例。
【问题讨论】:
-
也许应该是 react-router-dom 的工作原理?
标签: reactjs react-router react-router-dom