使用react-router-dom匹配url路径时,如何防止React组件卸载

时间:2021-01-23 00:19:14

标签: reactjs react-router-dom

我目前正在努力使用 React 及其库 react-router-dom。

为了简化:

我的应用组件中有这个:

const App = () => {

  return (
    <Router>
      <Layout>
        <Switch>
           // <Other Routes />
          <Route path='/product/:id' component={ProductScreen} />
          // <Other Routes />
        </Switch>
      </Layout>
    </Router>
  )
}

<ProductScreen />(单个产品视图)包装如下: enter image description here

<ProductNav /> 组件嵌入了来自 react-router-dom 的两个链接。它还包括到达上一个或下一个产品所需的逻辑。像这样例如:

<Link 
   className='prev'
   to={`/product/${currentIndex - 1 < 0 ? ids[lastIndex] : ids[currentIndex - 1]}`}
>
   Previous
</Link>

它可以工作,但我对这种方法并不满意,因为每次我点击“上一个”或“下一个”时 <ProductScreen /> 都会卸载,这会导致页面上出现一些不美观的东西。 我想阻止它卸载以便改为:

enter image description here

我尝试了很多东西,阅读了文档,但我现在很卡。如果有人对如何实现这一点有任何想法,我会很高兴阅读它。

1 个答案:

答案 0 :(得分:1)

您可以使用路由嵌套路由如下:

<Header />
<Main>
<Route path="/products" component={Product> />
</Main>
<Footer />

页面产品

const {url} = useRouteMatch();
render() {
    <>
       <Navbar />
       <Route path=`${url}/:id` component={ProductDetail} />
    </>

}