无法在反应中正确显示路线

时间:2020-06-04 12:41:24

标签: reactjs react-router

嗨,我在App.js中有这条路线

function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route key="products" path="/products" component={Products}></Route>
        <Route key="preview" path="/products/:id" component={Preview}></Route>
        <Route key="add-product" path="/products/create" component={ProductCreate}></Route>
        <Route key="edit-product" path="/products/:id/edit" component={ProductEdit}></Route>
        <Route exact path="/" component={Home}></Route>
      </Switch>
    </BrowserRouter>
  );
}

它仅显示/ products,//其他不显示,它们显示Products组件,我不明白为什么。 例如,我的产品编辑如下:

import React from 'react';

const ProductEdit = (props) => {
  return(
    <div>
      <p>Product Edit page</p>
    </div>
  )
}

export default ProductEdit;

这是我得到的结果:

enter image description here

我自己找不到问题...

2 个答案:

答案 0 :(得分:2)

您必须在Switch中组织路径,使前缀路径位于末尾。

当前代码的问题是,当您在路径/products/:id上时,它也与路径/products匹配,因为它是前缀路径,因此它仅呈现产品组件,而Switch仅呈现第一个匹配的路线

路径的重新排序版本如下

<BrowserRouter>
  <Switch>
    <Route key="edit-product" path="/products/:id/edit" component={ProductEdit}></Route>
    <Route key="add-product" path="/products/create" component={ProductCreate}></Route>
    <Route key="preview" path="/products/:id" component={Preview}></Route>
    <Route key="products" path="/products" component={Products}></Route>
    <Route exact path="/" component={Home}></Route>
  </Switch>
</BrowserRouter>

答案 1 :(得分:1)

/products/:id路径将与/products/create以及/products/:id/edit匹配,并且在您使用Switch时,一旦路由匹配,将不再呈现其他路由。

重新排序Route个组件将解决问题

<Route key="edit-product" path="/products/:id/edit" component={ProductEdit}></Route>
<Route key="add-product" path="/products/create" component={ProductCreate}></Route>
<Route key="preview" path="/products/:id" component={Preview}></Route>