反应路由器不重定向到页面

时间:2021-01-28 00:15:43

标签: reactjs react-router switch-statement react-router-dom

我在使用 react-router 时遇到问题

<Switch>
                    <Route path="/" exact >
                         HOME 
                    </Route>

                    <Route path="/cart"  >
                        <Cart />
                    </Route>

                    <Route path="/shop/category=:category">
                        <ShoppingList />
                    </Route>

                    <Route path="/shop/category=:category/product=:title"  >
                        <ProductInfo />
                    </Route>
 </Switch>

只要重定向到 /shop/category=:category 对我有用,重定向到 /shop/category=:category/product=:title 就不会显示组件 ProductInfo。我的链接将 window.location.pathname 设置为例如:/shop/category=Water%20sports/product=Fins

问题可能出在哪里?


我的链接在另一个文件中,我只是写了

const productLink = "/shop/category="+Item.category+"/product="+Item.title;
...
<Link to={productLink} >

1 个答案:

答案 0 :(得分:0)

问题在于您的 Route 的顺序。 React 路由器的设计是为了将用户发送到与他们当前的 path 匹配的第一个路由,不是最具体的路由。

当您的路径是另一路径的子集时,例如类别/产品到类别,您需要先列出更具体的路径。否则,所有类别/产品页面都将与该类别匹配。

<Switch>
    <Route path="/" exact >
          HOME 
    </Route>

    <Route path="/cart"  >
        <Cart />
    </Route>

    <Route path="/shop/category=:category/product=:title"  >
        <ProductInfo />
    </Route>

    <Route path="/shop/category=:category">
        <ShoppingList />
    </Route>
 </Switch>