是否有机会在路由中传递查询参数,例如 ?id= "idValue"?



我使用的是react路由器v4。我们可以在v4中以/user/:id?的形式传递查询参数?。但是,我需要在路由中传递查询参数,比如/user/?id="id"。

任何帮助或建议都是可观的。

您可以在位置对象上使用search属性,反应路由器将其传递给的所有组件

例如,如果您的路线是/user?id=1,则

console.log(this.props.location.search) // ?id=1

然后,您可以使用类似query-string的库来解析这些查询参数

import queryString from 'query-string'
// inside your component
const params = queryString.parse(this.props.location.search)
params.id === 1

您可以使用HOC来提取React Router提供的location对象的search属性并将其解析到底层组件。像这样:

const withQuery = Component => props => {
if (props.location && props.location.search) {
const query = props.location.search.substr(1)
.split('&')
.reduce((carry, pair) => {
const [ key, val ] = pair.split('=');
carry[unescape(key)] = unescape(val);
return carry;
}, {});
return <Component {...props} query={query} />
} else {
return <Component {...props} query={{}} />
}
}

并包装根据<Route />:渲染的组件

<Route
path="/query"
component={withQuery(MyComponent)}
/>

看一看这个沙箱,详细了解这个想法。

您可以使用如下上下文来完成,

import PropTypes from 'prop-types'
class Sample extends React.Component {
static get contextTypes() {
return {
router: PropTypes.object.isRequired,
};
}
.....
handleSubmit(data) {
let query = {}
query['id'] = data.id
this.context.router.push({
pathname:'/path',
query: query
});
}
}
}

相关内容

最新更新