首页 > 解决方案 > 在不卸载 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)重新呈现,即使它们位于子路由之外。

标签: reactjsreduxroutingreact-routerreact-router-dom

解决方案


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

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

例如看这个


推荐阅读