【发布时间】:2019-03-12 01:08:15
【问题描述】:
测试用例
https://codesandbox.io/s/rr00y9w2wm
重现步骤
或
预期行为
-
match.params.topicId应与父 Topics 组件相同,在 Topic 组件中访问时应与match.params.topicId相同
实际行为
-
match.params.topicId在 Topic 组件中访问时为 undefined -
match.params.topicId在 Topics 组件中访问时是 rendering
我从this closed issue 了解到,这不一定是错误。
此要求在想要在工厂 Web 应用程序中创建运行的用户中非常普遍,其中父级别的组件 Topics 需要访问 match.params.paramId 其中@987654334 @ 是匹配嵌套(子)组件 Topic 的 URL 参数:
const Topic = ({ match }) => (
<div>
<h2>Topic ID param from Topic Components</h2>
<h3>{match.params.topicId}</h3>
</div>
);
const Topics = ({ match }) => (
<div>
<h2>Topics</h2>
<h3>{match.params.topicId || "undefined"}</h3>
<Route path={`${match.url}/:topicId`} component={Topic} />
...
</div>
);
在一般意义上,Topics 可以是抽屉或导航菜单组件,Topic 可以是任何子组件,就像在我正在开发的应用程序中一样。子组件有它自己的:topicId 参数,它有它自己的(比如说)<Route path="sections/:sectionId" component={Section} /> Route/Component。
更痛苦的是,导航菜单不必与组件树建立一对一的关系。有时菜单根级别的项目(例如Topics、Sections 等)可能对应于 嵌套 结构(Sections 仅在主题下呈现,/topics/:topicId/sections/:sectionId 虽然它有自己的规范化列表,用户可以在导航栏中的标题 Sections 下使用)。
因此,当 Sections 被点击时,it 应该被突出显示,而不是 Sections 和 Topics。
由于位于应用程序根级别的导航栏组件无法使用sectionId 或sections 路径,因此有必要为这种常见的用例编写hacks like this。
我根本不是 React Router 方面的专家,所以如果有人可以为这个用例冒险一个适当的优雅解决方案,我会认为这是一项富有成果的努力。优雅,我的意思是
- 使用
match而不是history.location.pathname - 不涉及像手动解析
window.location.xxx这样的hacky方法 - 不使用
this.props.location.pathname - 不使用第三方库,如
path-to-regexp - 不使用查询参数
其他技巧/部分解决方案/相关问题:
TIA!
【问题讨论】:
标签: javascript reactjs routing nested react-router