如何避免路线碰撞?

时间:2017-08-25 04:48:23

标签: javascript reactjs react-router jsx

我想在用户访问<Product>时呈现/Products/1

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

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

<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} />;

1 个答案:

答案 0 :(得分:3)

使用new_profile = Profile.objects.create( user = currentUser, first_name = first_name, last_name = last_name, dob_month = int(dob_month), dob_day = int(dob_day), dob_year = int(dob_year), city = city, state = state, phone = phone, privacy = privacy, )

<Switch />

它会尝试找到第一场比赛。 因此<Switch> <Route exact path="/Products/new" component={CreateProduct} /> <Route exact path="/Products/:productId" component={Product} /> </Switch> 将匹配第一条路线并跳过第二条路线。 /Products/new将匹配第二个。

相关问题