所以,目前,我有一个路由组件:
<Route path="/lists/:query" component={Lists} />
我接到一个电话,例如:
http://localhost:4567/lists/page=17&city_codes=2567
在我的Lists
组件中,我以这种方式处理此查询:
componentDidMount() {
const query = match.params.query;
const cleanQueryString = query.replace(/[|;$%@"<>()+,]/g, '');
// break up the string using '&' and '=' into an object
const properties = this.queryURL(cleanQueryString);
const cleanQueryObj = _.pick(Object.assign({}, ...properties), [
'page',
'city_codes',
'min_monthly_fee',
'max_monthly_fee',
'order_by',
]);
// update the query object based on component state
this.setState({ query: cleanQueryObj }, () => {
cleanQueryObj.page && this.updateIndex(parseInt(cleanQueryObj.page, 10));
});
// call axios request and update redux
dispatch(handleLists(cleanQueryObj));
// update browser url
this.props.history.push(cleanQueryObj);
现在,我看到很多主要网站在查询之前使用?q=
,我想知道我错过了什么或可以改进什么?
思潮?
虽然你正在做的事情在技术上是有效的,但它有点不标准。您使用路由器的方式:query
参数及其格式化方式,看起来就像实际的location.search
参数格式,而不是路径参数。
一种更标准的方法是使用以下 URL:
http://localhost:4567/lists?page=17&city_codes=2567
并按如下方式编写代码:
// In your routes, just a simple route with no path params
<Route path="/lists" component={Lists} />
// In your component
import queryString from 'query-string'
[...]
componentDidMount() {
// Use location object from react-router
const { search } = this.props.location
// Parse it using a npm dedicated module
const { page, city_codes } = queryString.parse(search)
// Now you can use those params
]);
编辑:现在是问题的实际答案:
?q=blah
通常用于搜索上下文,q
参数是用于搜索某些内容的字符串。下面可以有其他参数,例如?q=blah&ext=txt
.
因此,它与:query
路径参数不同,后者被编码为包含多个参数,而此处q
是一个即用型参数。