栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在父路径组件中获取参数

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在父路径组件中获取参数

@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-router
API,该API也用于路由器中的路径匹配。我们也不
window.location
在这里使用,因此如果您还导出原始组件,则测试/模拟将很容易。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/379414.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号