如何解析URL在reactJs中添加参数

时间:2019-05-27 13:33:06

标签: reactjs react-router-dom

我正在使用react-router-dom来解析一个URL,即我当前的URL

  

localhost:3000 / q = sldkfjsdlkjflksfd

但是我想要在URL &test=1

中添加一个新参数
  

localhost:3000 / q = sldkfjsdlkjflksfd&test = 1

const parsed = parse(window.location.search);

1 个答案:

答案 0 :(得分:0)

您可以使用HTML Api URLSearchParams

componentDidMount(){
  let params = new URLSearchParams(this.props.location.search);  
  let q = params.get('q');
  let test = params.get('test');
}

此外,如果未定义this.props.location并且import { withRouter } from 'react-router-dom';

,则在组件中使用export default withRouter(ComponentName);