我在客户端为我的应用程序使用 react 和 react-router。我似乎无法弄清楚如何从 url 中获取以下查询参数,例如:
http://xmen.database/search#/?status=APPROVED&page=1&limit=20
我的路线看起来像这样(我知道路径完全错误):
var routes = (
<Route>
<DefaultRoute handler={SearchDisplay}/>
<Route name="search" path="?status=:status&page=:page&limit=:limit" handler={SearchDisplay}/>
<Route name="xmen" path="candidate/:accountId" handler={XmenDisplay}/>
</Route>
);
我的路线运行良好,但我只是不确定如何格式化路径以获得我想要的参数。感谢您对此的任何帮助!
getCurrentQuery
找到在组件中提取查询字符串参数的示例
willTransitionTo
挂钩。它接收查询字符串参数。 github.com/rackt/react-router/commit/…
注意:从评论中复制/粘贴。一定要喜欢原帖!
用 es6 编写并使用 react 0.14.6 / react-router 2.0.0-rc5。我使用此命令在我的组件中查找查询参数:
this.props.location.query
它在 url 中创建所有可用查询参数的哈希。
更新:
对于 React-Router v4,请参阅 this answer。基本上,使用 this.props.location.search
获取查询字符串并使用 query-string
包或 URLSearchParams 进行解析:
const params = new URLSearchParams(paramsString);
const tags = params.get('tags');
上述答案在 react-router v4
中不起作用。这是我为解决问题所做的 -
首先安装解析所需的 query-string。
npm install -save query-string
现在在路由组件中,您可以像这样访问未解析的查询字符串
this.props.location.search
您可以通过登录控制台进行交叉检查。
最后解析访问查询参数
const queryString = require('query-string');
var parsed = queryString.parse(this.props.location.search);
console.log(parsed.param); // replace param with your own
因此,如果查询类似于 ?hello=world
console.log(parsed.hello)
将记录 world
const query = new URLSearchParams(props.location.search); console.log(query.get('hello'));
(旧浏览器需要 polyfill)。
旧(前 v4):
用 es6 编写并使用 react 0.14.6 / react-router 2.0.0-rc5。我使用此命令在我的组件中查找查询参数:
this.props.location.query
它在 url 中创建所有可用查询参数的哈希。
更新(反应路由器 v4+):
React Router 4 中的 this.props.location.query 已被删除(当前使用 v4.1.1)更多关于这里的问题:https://github.com/ReactTraining/react-router/issues/4410
看起来他们希望您使用自己的方法来解析查询参数,目前使用此库来填补空白:https://github.com/sindresorhus/query-string
TypeError: Cannot read property 'location' of undefined
:|
更新 2017.12.25
"react-router-dom": "^4.2.2"
网址喜欢
BrowserHistory
:http://localhost:3000/demo-7/detail/2?sort=name
HashHistory
:http://localhost:3000/demo-7/#/detail/2?sort=name
具有 query-string 依赖性:
this.id = props.match.params.id;
this.searchObj = queryString.parse(props.location.search);
this.from = props.location.state.from;
console.log(this.id, this.searchObj, this.from);
结果:
2 {sort: "name"} home
"react-router": "^2.4.1"
类似 http://localhost:8080/react-router01/1?name=novaline&age=26
的网址
const queryParams = this.props.location.query;
queryParams 是一个包含查询参数的对象:{name: novaline, age: 26}
http://localhost:8090/#access_token=PGqsashgJdrZoU6hV8mWAzwlXkJZO8ImDcn&expires_in=7200&token_type=bearer
(即 #
之后没有 /
)那么对于 react router v4 你应该使用 location.hash
而不是 location.search
"react-router-dom": "^5.0.0",
您不需要添加任何额外的模块,只需在具有如下 url 地址的组件中:
http://localhost:3000/#/?authority'
您可以尝试以下简单代码:
const search =this.props.location.search;
const params = new URLSearchParams(search);
const authority = params.get('authority'); //
使用 stringquery 包:
import qs from "stringquery";
const obj = qs("?status=APPROVED&page=1limit=20");
// > { limit: "10", page:"1", status:"APPROVED" }
使用查询字符串包:
import qs from "query-string";
const obj = qs.parse(this.props.location.search);
console.log(obj.param); // { limit: "10", page:"1", status:"APPROVED" }
无包装:
const convertToObject = (url) => {
const arr = url.slice(1).split(/&|=/); // remove the "?", "&" and "="
let params = {};
for(let i = 0; i < arr.length; i += 2){
const key = arr[i], value = arr[i + 1];
params[key] = value ; // build the object = { limit: "10", page:"1", status:"APPROVED" }
}
return params;
};
const uri = this.props.location.search; // "?status=APPROVED&page=1&limit=20"
const obj = convertToObject(uri);
console.log(obj); // { limit: "10", page:"1", status:"APPROVED" }
// obj.status
// obj.page
// obj.limit
希望有帮助:)
快乐编码!
在阅读了其他答案(首先是@duncan-finney,然后是@Marrs)之后,我着手查找更改日志,该日志解释了解决此问题的惯用 react-router 2.x 方法。组件中的 documentation on using location(您需要查询)实际上与实际代码相矛盾。所以如果你听从他们的建议,你会收到这样的愤怒警告:
Warning: [react-router] `context.location` is deprecated, please use a route component's `props.location` instead.
事实证明,您不能有一个名为 location 的上下文属性使用 location 类型。但是您可以使用一个名为 loc 的上下文属性,它使用位置类型。所以解决方案是对它们的源代码进行小修改,如下所示:
const RouteComponent = React.createClass({
childContextTypes: {
loc: PropTypes.location
},
getChildContext() {
return { location: this.props.location }
}
});
const ChildComponent = React.createClass({
contextTypes: {
loc: PropTypes.location
},
render() {
console.log(this.context.loc);
return(<div>this.context.loc.query</div>);
}
});
您也可以只将您想要的位置对象的部分传递给您的孩子获得相同的好处。它没有更改警告以更改为对象类型。希望有帮助。
简单的js解决方案:
queryStringParse = function(string) {
let parsed = {}
if(string != '') {
string = string.substring(string.indexOf('?')+1)
let p1 = string.split('&')
p1.map(function(value) {
let params = value.split('=')
parsed[params[0]] = params[1]
});
}
return parsed
}
您可以使用以下命令从任何地方调用它:
var params = this.queryStringParse(this.props.location.search);
希望这可以帮助。
使用 query-string 模块创建优化的生产构建时,您可能会收到以下错误。
无法缩小此文件中的代码:./node_modules/query-string/index.js:8
为了克服这个问题,请使用名为 stringquery 的替代模块,它可以很好地完成相同的过程,在运行构建时不会出现任何问题。
import querySearch from "stringquery";
var query = querySearch(this.props.location.search);
query
似乎在 React Router 4 中消失了。github.com/ReactTraining/react-router/issues/…