2017-08-25 69 views
1

我想在用户访问/Products/1时呈现<Product>如何避免路线碰撞?

我想在用户访问/Products/new时呈现<CreateProduct>

我的路由器看起来像这样:

<Route exact path="/Products/new" component={CreateProduct} /> 
<Route exact path="/Products/:productId" component={Product} /> 

如果用户浏览到/Products/new,它既路线和结果相匹配的Product组件引发错误重新:没有找到产品id为new

我一直无法在react-router文档中找到任何内容来避免这种情况。我可能会使用这个技巧,但必须有一个 “更好” 的方式:

<Route exact path="/Products/new" component={CreateProduct} /> 
<Route exact path="/Products/:productId" render={renderProduct} /> 

使用函数来呈现<Product>路线:

const renderProduct = props => 
    props.match.params.productId === 'new' 
    ? null 
    : <Product {...props} />; 

回答

3

使用<Switch />

<Switch> 
    <Route exact path="/Products/new" component={CreateProduct} /> 
    <Route exact path="/Products/:productId" component={Product} /> 
</Switch> 

它会尝试找到第一个匹配项。 因此/Products/new将匹配第一条路线并跳过第二条路线。 /Products/1将匹配第二个。

+0

那正是我所需要的。我想我的google foo没有达到标准。当计时器允许时会接受 –

+0

您使用react-router v4,对不对?比以前的版本更容易理解。 – Win

+0

您可以阅读:https://reacttraining.com/react-router/web/example/ambiguous-matches – Win