@Kyle从技术角度很好地解释了这个问题。我将只专注于解决该问题。
您可以
matchPath用来获取
id所选项目。
matchPath - https: **//reacttraining.com/react-
router/web/api/matchPath**
这使您可以使用与正常渲染周期之外的代码相同的匹配代码,例如在服务器上渲染之前收集数据依赖性。
这种情况下的用法非常简单。
1使用 matchPath
// history is one of the props passed by react-router to component// @link https://reacttraining.com/react-router/web/api/historyconst match = matchPath(history.location.pathname, { // You can share this string as a constant if you want path: "/articles/:id"});let articleId;// match can be nullif (match && match.params.id) { articleId = match.params.id;}2 articleId
在渲染中使用
{articleId && ( <h1>You selected article with id: {articleId}</h1>)}我构建了一个简单的演示,您可以用来在项目中实现相同的功能。
演示: https :
//presandbox.io/s/pQo6YMZop
我认为该解决方案非常优雅,因为我们使用了官方
react-routerAPI,该API也用于路由器中的路径匹配。我们也不
window.location在这里使用,因此如果您还导出原始组件,则测试/模拟将很容易。



