在不卸载 MainRoute 的情况下切换子路由 (React-Router-Dom)



>UPDATE(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>

我希望应用程序在导航子路由(源/集合)时保持挂载状态,但是在切换子路由时应用程序正在卸载并重新安装。这会导致应用程序中的组件(如侧边栏和建议)重新渲染,即使它们位于子路由之外。

将嵌套Route组件中的path='/home/collections'替换为path={`${match.path}/collections`}

并将链接中的to='/home/collections'替换为to={`${match.url}/collections`}

例如,请参阅此内容

最新更新