问题
I have a /cart
route that accepts a couple of query params called validate
and email
. They’re only used when a user isn’t logged in and are unnecessary when they are. In the latter case I would like to remove them from the URL.
This is my current onEnter
function for the /cart
route:
const requireCartLogin = (props, replace) => {
const { email, validate } = props.location.query;
// Exit process if the 'validate' query isn’t present.
if (typeof validate === 'undefined') { return; }
if (!isAuthenticated() || requiresReauthentication()) {
replace({
pathname: '/account/signin',
query: { step: 'signin' },
state: {
email: typeof email !== 'undefined' ? email : null,
auth: true,
next: '/cart'
}
});
} else if (isAuthenticated()) {
replace({
pathname: '/cart',
query: null
});
}
};
It’s that second part of the conditional that should be removing the query params, but it isn’t currently working. What am I missing here?
回答1:
Have a look at Dimitry Dushin's example
Create 2 utility functions like this:
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);
};
And use it to manipulate the query as in the example shown below:
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);
Note that this will not work in >v4 of react-router
.
来源:https://stackoverflow.com/questions/50952473/how-do-you-remove-query-params-from-the-current-route