Answers:
在push
中hashHistory
,您可以指定查询参数。例如,
history.push({
pathname: '/dresses',
search: '?color=blue'
})
要么
history.push('/dresses?color=blue')
您可以查看此存储库以获取有关使用的其他示例history
router.push({ pathname: '/path', state: { color: 'blue', size: 10 }, });
使用react-router v4,redux-thunk和react-router-redux(5.0.0-alpha.6)软件包的示例。
当用户使用搜索功能时,我希望他能够将相同查询的URL链接发送给同事。
import { push } from 'react-router-redux';
import qs from 'query-string';
export const search = () => (dispatch) => {
const query = { firstName: 'John', lastName: 'Doe' };
//API call to retrieve records
//...
const searchString = qs.stringify(query);
dispatch(push({
search: searchString
}))
}
react-router-redux
已弃用
withReducer
HOC中,这将为您提供history
支持。然后您可以运行history.push({ search: querystring }
。
react-router-redux
,你可以用connected-react-router
它不会被弃用。
约翰的答案是正确的。当我处理参数时,我还需要URLSearchParams
接口:
this.props.history.push({
pathname: '/client',
search: "?" + new URLSearchParams({clientId: clientId}).toString()
})
您可能还需要用withRouter
HOC 包装组件,例如。export default withRouter(YourComponent);
。
withRouter
是一个HOC,而不是一个装饰器
for react-router v4.3,
const addQuery = (key, value) => {
let pathname = props.location.pathname;
// returns path: '/app/books'
let searchParams = new URLSearchParams(props.location.search);
// returns the existing query string: '?type=fiction&author=fahid'
searchParams.set(key, value);
this.props.history.push({
pathname: pathname,
search: searchParams.toString()
});
};
const removeQuery = (key) => {
let pathname = props.location.pathname;
// returns path: '/app/books'
let searchParams = new URLSearchParams(props.location.search);
// returns the existing query string: '?type=fiction&author=fahid'
searchParams.delete(key);
this.props.history.push({
pathname: pathname,
search: searchParams.toString()
});
};
```
```
function SomeComponent({ location }) {
return <div>
<button onClick={ () => addQuery('book', 'react')}>search react books</button>
<button onClick={ () => removeQuery('book')}>remove search</button>
</div>;
}
```
// To know more on URLSearchParams from
[Mozilla:][1]
var paramsString = "q=URLUtils.searchParams&topic=api";
var searchParams = new URLSearchParams(paramsString);
//Iterate the search parameters.
for (let p of searchParams) {
console.log(p);
}
searchParams.has("topic") === true; // true
searchParams.get("topic") === "api"; // true
searchParams.getAll("topic"); // ["api"]
searchParams.get("foo") === null; // true
searchParams.append("topic", "webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
searchParams.set("topic", "More webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
searchParams.delete("topic");
searchParams.toString(); // "q=URLUtils.searchParams"
[1]: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
import { browserHistory } from 'react-router';
/**
* @param {Object} query
*/
export const addQuery = (query) => {
const location = Object.assign({}, browserHistory.getCurrentLocation());
Object.assign(location.query, query);
// or simple replace location.query if you want to completely change params
browserHistory.push(location);
};
/**
* @param {...String} queryNames
*/
export const removeQuery = (...queryNames) => {
const location = Object.assign({}, browserHistory.getCurrentLocation());
queryNames.forEach(q => delete location.query[q]);
browserHistory.push(location);
};
要么
import { withRouter } from 'react-router';
import { addQuery, removeQuery } from '../../utils/utils-router';
function SomeComponent({ location }) {
return <div style={{ backgroundColor: location.query.paintRed ? '#f00' : '#fff' }}>
<button onClick={ () => addQuery({ paintRed: 1 })}>Paint red</button>
<button onClick={ () => removeQuery('paintRed')}>Paint white</button>
</div>;
}
export default withRouter(SomeComponent);
当需要一个模块来轻松解析查询字符串时,建议使用查询字符串模块。
componentWillMount() {
var query = queryString.parse(this.props.location.search);
if (query.token) {
window.localStorage.setItem("jwt", query.token);
store.dispatch(push("/"));
}
}
在这里,成功进行Google-Passport身份验证后,我将从Node.js服务器重定向回我的客户端,该身份验证使用令牌作为查询参数进行重定向。
我正在使用查询字符串模块对其进行解析,保存并使用react-router-redux中的 push更新URL中的查询参数。
我希望您使用下面的ES6
样式函数:
getQueryStringParams = query => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split('&')
.reduce((params, param) => {
let [key, value] = param.split('=');
params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
return params;
}, {}
)
: {}
};
也可以这样写
this.props.history.push(`${window.location.pathname}&page=${pageNumber}`)