reactjs - 如何将组件添加到 window.location.href?
问题描述
我正在尝试根据用户的点击为我拥有的每个项目设置一个自定义 URL。当用户单击“查看项目”时,我想重定向到具有项目名称和 ID 的自定义 URL,例如:“http://localhost:3000/item-1/-MC_xbIMm8zctEWRJ-Lj/”。但是,我只是得到一个空白页。我使用以下代码使这成为可能:
<Button style={{color: '#fff',display: 'flex', padding: 0, paddingLeft: "5px"}} startIcon={<AddShoppingCartIcon/>}
onClick={() => this.routeChange(itemKeys[key].name,itemKeys[key].id )}> View Item </Button>
而在对应的函数中是(routeChange):
routeChange(name, id) {
var parameter1 = name.replace(/\s+/g, '-');
var parameter2 = id;
window.location.href="/"+parameter1+"/"+parameter2+"/";
}
现在我的问题是,如何向此自定义 URL 添加组件?我试着做类似的事情
<Route path="/${itemKey[key].name}/${itemKey[key].id}" component={Item} />
这不起作用,因为它只是将变量作为字符串并没有得到我想要的路线。如何将组件添加到我的 window.location.href,并且没有空白页?或者有没有更好的方法来创建自定义 URL?
解决方案
看看 React 路由器的URL 参数示例。如果你想拥有带有变量的 URL,你可以有这样的路由:
<Route path="/:name/:id" component={Item} />
在项目组件中,您可以通过钩子获取name
和id
参数。useParams
推荐阅读
- excel - COUNTIFS formula - unique values
- regex - 正则表达式 - 从起点到终点抓取单词
- android - OSM 奖励包 - OSRMRoadManager::getRoad: 请求失败
- javascript - Web 应用程序如何将浏览器带到前台?
- javascript - 防止长按选择附近的文本
- markdown - Pandoc:如何在将 md 渲染为 pdf 时保持图像和字幕的顺序
- javascript - 使用 JavaScript 进行 api 发布请求后如何在 Laravel 中闪烁消息?
- sql - 在 SQL 中加入 2 个不重复的表
- google-sheets - 有人可以告诉我为什么谷歌表格上的这种条件格式没有突出显示 J8/9
- python - 协程和异步/等待