当我使用"链接"在嵌套路由(子路由)之间切换时,父组件会卸载。有什么办法可以避免这种情况吗?



更新:此代码有问题。我已在下方回答

这是我的外部"应用程序"组件。在这个我有一个"仪表板"组件路线

export default function App() {
return (
<Router>
<div>
<hr />
<Switch>
<Route exact path="/">
<Redirect to="/dashboard" />
</Route>
<Route path="/dashboard" component={Dashboard} />
<Route path="*" component={() => <h1>not found</h1>} />
</Switch>
</div>
</Router>
);
}

"Dashboard"组件包含到"Home"one_answers"Chat"组件的嵌套路由

function Dashboard({ match }) {
useEffect(() => {
console.log("dashboard mounted");
return () => console.log("dashboard unmounted");
});
return (
<div>
<Switch>
<Route exact path={`${match.path}`} component={Home} />
<Route exact path={`${match.path}/chat`} component={Chat} />
</Switch>
</div>
);
}

"主页"one_answers"聊天"组件

function Home({ match }) {
useEffect(() => {
console.log("home mounted");
return () => console.log("home unmounted");
});
return (
<div>
<h3>home component</h3>
<Link to={`${match.url}/chat`}>
<button>chat</button>
</Link>
</div>
);
}
function Chat() {
useEffect(() => {
console.log("chat mounted");
return () => console.log("chat unmounted");
});
return (
<div>
<h3>Chat component</h3>
</div>
);
}

问题是当我从"主页"导航到"聊天"时,"仪表板"(父(组件会卸载。我想避开这个

codeSandBox

检查控制台

我上面的代码有问题。实际上,如果存在嵌套路由,并且我们在它们之间切换,React路由器不会卸载父组件。我忘记在"Dashboard"、"Home"one_answers"Chat"中添加空的依赖数组。现在控制台消息显示"仪表板已卸载"。

来自react文档:
如果您想运行一个效果并只清理一次(在装载和卸载时(,您可以传递一个空数组([](作为第二个参数

不能嵌套不同的<Switch />标记。

export default function App() {
useEffect(() => {
console.log("app mounted");
return () => console.log("app unmounted");
});
return (
<Router>
<div>
<hr />
<Switch>
<Route exact path="/">
<Redirect to="/dashboard" />
</Route>
<Route path="/dashboard/chat" component={Chat} />
<Route path="/dashboard" component={Home} />
<Route path="*" component={() => <h1>not found</h1>} />
</Switch>
</div>
</Router>
);
}

最新更新