首页 > 解决方案 > 如何将组件添加到 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?

标签: reactjsmaterial-uireact-router-dom

解决方案


看看 React 路由器的URL 参数示例。如果你想拥有带有变量的 URL,你可以有这样的路由:

<Route path="/:name/:id" component={Item} />

在项目组件中,您可以通过钩子获取nameid参数。useParams


推荐阅读