Reactjs 从URL查询获取URL参数
目标:从URL检索Id 我有一个具有以下代码的产品提要:Reactjs 从URL查询获取URL参数,reactjs,Reactjs,目标:从URL检索Id 我有一个具有以下代码的产品提要: 这是我的源代码: {products.map((产品)=>( ))} 以及创建URL的ProductCard组件: {brand} {name} {id} {} 单击单个产品时,我将被重定向到单个产品页面: 函数DetailProductPage({id}){ const productId={id}; 返回( 产品页 {id} ); } 当我走这条路线时,我会得到一个带有产品参数的URL:(例如,http://localh
这是我的源代码:
{products.map((产品)=>(
))}
以及创建URL的ProductCard
组件:
{brand}
{name}
{id}
{}
单击单个产品时,我将被重定向到单个产品页面:
函数DetailProductPage({id}){
const productId={id};
返回(
产品页
{id}
);
}
当我走这条路线时,我会得到一个带有产品参数的URL:(例如,http://localhost:3000/product/6CeJGSm7dBTABs8rRBJh
)
如何查询URL的
6CeJGSm7dBTABs8rRBJh
部分并将其放入变量中?如下代码从URL获取产品id:
const params=useparms();
我假设您正在为此使用react路由器dom。有几种方法可以从URL检索此值,但使用提供的代码最简单的方法是使用useParams
hook,如下所示:
从'react router dom'导入{useParams};
函数DetailProductPage({id}){
const{productId}=useParams();
返回(
产品页
{productId}
);
}
此处的更多信息:导出组件时,您需要使用
with router
访问此参数:
import { withRouter } from 'react-router-dom';
export default withRouter(ComponentName);
您的参数现在在props
中。就你而言:
const productId = props.match.params.productId;
或(使用分解):
您可以使用javascript提供的对象解析url 要获取当前位置,您可以使用
window.location
所以通过结合Url和位置
let urlArr = new URL(window.location).href.split('/');
console.log(urlArr[urlArr.length - 1]);
这将记录6CeJGSm7dBTABs8rRBJh
let urlArr = new URL(window.location).href.split('/');
console.log(urlArr[urlArr.length - 1]);