我有一个 /cart
接受几个名为 validate
的查询参数的路由和 email
.它们仅在用户未登录时使用,并且在用户登录时是不必要的。在后一种情况下,我想从 URL 中删除它们。
这是我现在的 onEnter
/cart
的函数路线:
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
});
}
};
条件的第二部分应该删除查询参数,但它目前不起作用。我在这里缺少什么?
最佳答案
看看 Dimitry Dushin 的 example
创建 2 个实用函数,如下所示:
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);
请注意,这在
react-router
的 >v4 中不起作用.
关于reactjs - 如何从当前路由中删除查询参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50952473/