嗨,我在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;
这是我得到的结果:
我自己找不到问题...
答案 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>