如何在React项目中提取URL路径中的指定片段
解决方案
前提说明
- 首先确保你的React Router路由配置中对应路径已经声明了动态参数占位符,示例配置如下:
// 你的路由配置处 <Route path="/page/:pageId" element={/* 你的页面组件,Sidebar通常作为公共组件在页面内引入即可 */} />
这里的:pageId就是你要提取的数字片段对应的参数名,你可以根据业务需求自定义参数名。
代码修改说明
你已经使用withRouter高阶组件包裹了Sidebar组件,withRouter会自动将路由相关的match、location、history对象注入到组件的props中,你可以直接通过this.props.match.params.参数名获取到对应URL片段。
另外你原有代码的导出语句多了一个多余的右括号,我同步做了修正。
修改后完整代码
import React, { Component } from 'react'; import { withRouter, Link } from 'react-router-dom'; import { compose } from 'redux'; import { connect } from 'react-redux'; import { push } from 'connected-react-router'; class Sidebar extends Component { constructor(props) { super(props); this.state = {}; } render() { // 提取URL中的pageId就是你需要的123456这类片段 const pageId = this.props.match.params.pageId; return ( <div> URL segment: {pageId} </div> ); } } // 修正了原有代码多余的右括号 export default compose(withRouter)(Sidebar);
备用方案(无动态路由配置场景)
如果你没有提前在路由中声明动态参数,也可以直接从路径字符串中手动拆分获取:
render() { const pathArr = this.props.location.pathname.split('/'); // 路径为page/123456的话,split后数组为['', 'page', '123456'],取最后一位元素即可 const pageId = pathArr[pathArr.length - 1]; return ( <div> URL segment: {pageId} </div> ); }
内容的提问来源于stack exchange,提问作者Cudos
相关产品推荐
相关产品推荐

