reactjs - 在不卸载 MainRoute 的情况下切换子路由(React-Router-Dom)
问题描述
更新(2019 年 5 月 19 日):从应用程序中删除withRouter
成功了。现在只有子路由按预期卸载/安装。
我想在不卸载父路由的情况下在子路由之间切换。(即从 /home/feed 到 /home/collections,不应卸载并重新安装 Home 组件(父路由);它应该只卸载 Feed 组件并安装 Collections 组件。
在应用程序中:
<Switch>
<Route component={home(LandingPage)} path='/' exact />
<Route component={index(Home)} path='/home' />
<Route component={index(Browse)} path='/browse' />
<Route component={index(Social)} path='/social' />
<Route component={index(Notifications)} path='/notifications' />
<Route component={index(Profile)} path='/profile/:id' />
<Route component={index(SinglePost)} path='/status/:id' />
<Route component={index(Settings)} path='/settings' />
<Route component={NoMatch} />
</Switch>
在家:
<Container>
<Sidebar
auth={auth}
user={user}
posts={posts}
followers={followers}
following={following}
fetchFollowers={fetchFollowers}
fetchFollowing={fetchFollowing}
/>
<Wrapper>
<Tabs>
<Tab>
<NavLink exact to='/home/feed'>
Feed
</NavLink>
</Tab>
<Tab>
<NavLink to='/home/collections'>Collections</NavLink>
</Tab>
<Tab>
<NavLink to='/home/locker'>Locker(α)</NavLink>
</Tab>
</Tabs>
<TabWrapper>
<Switch>
<Route
exact
path={['/home', '/home/feed']}
render={props => (
<Feed
{...props}
auth={auth}
user={user}
searchTerm={searchTerm}
populateNotification={populateNotifications}
/>
)}
/>
<Route
path='/home/collections'
render={props => (
<Collections
{...props}
userId={auth.id}
searchTerm={searchTerm}
posts={posts}
deletePost={deletePost}
fetchPosts={fetchPosts}
/>
)}
/>
<Route
path='/home/locker'
render={props => (
<Likes
{...props}
auth={auth}
locker={locker}
fetchUser={fetchUser}
fetchLocker={fetchLocker}
likedPosts={likedPosts}
/>
)}
/>
</Switch>
</TabWrapper>
</Wrapper>
<Suggested
auth={auth}
suggested={suggested}
fetchUser={fetchUser}
fetchSuggested={fetchSuggested}
fetchFollowing={fetchFollowing}
followAUser={followAUser}
/>
</Container>
我希望 App 在导航子路由(Feed/Collections)时保持挂载,但在切换子路由时 App 正在卸载和重新挂载。这会导致 App 中的组件(例如 Sidebar 和 Suggested)重新呈现,即使它们位于子路由之外。
解决方案
path='/home/collections'
在嵌套Route
组件中替换为path={`${match.path}/collections`}
并to='/home/collections'
在链接中替换为to={`${match.url}/collections`}
例如看这个
推荐阅读
- php - Laravel 与 artisan serve 合作,但不适用于 vhost
- php - InvalidArgumentException: "\string$filter" 不是 $objectManager->get() 的有效 Fqsen
- email - 从 Protonmail 将邮件导入 Mailcow
- php - Laravel - 为什么在我的工厂中,员工在创建完成之前而不是之后工作?
- angular - 将 Routerlink 作为字符串检索?
- layout - Graphviz:在三个集群中的节点之间创建具有直边的流程图
- ios - Swift:处理自定义幻灯片菜单中的快速滑动
- ios - Yelp API 业务匹配端点
- javascript - 如何在本地存储中保存用户输入(添加和删除)?
- python - 使用回调函数更新破折号数据表