我有一个例子,我想在表单上设置 url-scheme
/items/ <- list of items
/items/1 <- item1
/items/2 <- item2
...
/items/2 <- itemn
/items/new <- create item
根据我使用其他路由框架的经验,我尝试过以下方法:
function (props) {
var match = props.match;
return (
<div>
<Route path={ `${match.url}/new` }
component={ Create } />
<Route path={ `${match.url}/:id` }
component={ Details } />
<Route exact
path={ match.url }
component={ List } />
</div>
);
}
但是,当我导航到/items/new 时,创建组件和详细组件都会呈现。
我的解决方法是像这样包装详细信息组件:
function DetailContainer (props) {
if (props.match.params.id === 'new') {
return null;
}
return (
<Detail {...props} />
);
}
但这对我来说似乎有点老套。是否可以仅使用路由来设置这种行为?我知道这就是 Flask 中的工作方式,但从我从 rr4 文档中收集到的信息来看,这里的路由概念有点不同(意味着可以同时渲染多个路由)。
最佳答案
路由器的路径部分似乎基于此模块:https://www.npmjs.com/package/path-to-regexp
因为看起来您可以在路径部分中使用正则表达式,所以您不能使用
path={ `${match.url}/(:id?!new)` }
或者其他什么..(我的正则表达式目前还不是很好)
关于react-router - react 路由器4 : either-or routes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43890603/