在我的项目中,我使用了react路由器-dom 4.0.0-beta.6。我有如下代码:
<Route exact path="/home" component={HomePage}/>我希望在HomePage组件中获得查询参数。我找到了location.search param,它看起来像这样:?key=value,所以它是未解析的。
使用react路由器v4获得查询参数的正确方法是什么?
发布于 2017-04-05 02:06:09
解析查询字符串的能力已从V4中删除,因为多年来一直有支持不同实现的请求。这样,团队决定最好由用户来决定实现是什么样子的。我们建议导入查询字符串库。这是我用的
const queryString = require('query-string');
const parsed = queryString.parse(props.location.search);您还可以使用new URLSearchParams,如果您想要本地的东西,并且它可以满足您的需要。
const params = new URLSearchParams(props.location.search);
const foo = params.get('foo'); // bar您可以阅读更多关于决策这里的内容。
发布于 2020-05-12 20:10:36
另一个有用的方法是像这样使用开箱即用的URLSearchParams;
let { search } = useLocation();
const query = new URLSearchParams(search);
const paramField = query.get('field');
const paramValue = query.get('value');干净,可读性强,不需要模块。下面是更多的信息;
https://stackoverflow.com/questions/43216569
复制相似问题