英文:
How can I remove query string from React app, in a case-insensitive way?
问题
我找到了 https://stackoverflow.com/a/73353425/21065649,基本上使用了 `react-router-dom` 中的 `useSearchParams` 来移除查询字符串参数。
但是,在我的情况下,我正在使用一个键的数组,我必须循环遍历它们来移除参数。
问题在于大小写敏感性。
const [searchParams, setSearchParams] = useSearchParams();
const keys = ['Title', 'State'];
for (let index in keys) {
if (searchParams.has(keys[index]) { // 我希望这是不区分大小写的
seearchParams.delete(keys[index])
}
}
我不知道如何做到这一点。
英文:
I found https://stackoverflow.com/a/73353425/21065649 which basically uses useSearchParams
from react-router-dom
to remove query string parameters.
However, in my case, I'm using an array of keys and I have to loop over them to remove params.
The problem is case sensitivity.
const [searchParams, setSearchParams] = useSearchParams();
const keys = ['Title', 'State']
for (let index in keys) {
if (searchParams.has(keys[index]) { // I want this to be case-insensitive
seearchParams.delete(keys[index])
}
}
I don't know how to do that.
答案1
得分: 1
使用 .filter() 方法。筛选的结果是一个不在 keys 数组中的键的数组(比如 Title 和 State)。
应该在应用筛选之后调用 setSearchParams,就像这样:
const [searchParams, setSearchParams] = useSearchParams();
const keys = ['Title', 'State'];
const filteredParams = searchParams.filter((key) => !keys.includes(key.toLowerCase()));
filteredParams.forEach((key) => searchParams.delete(key));
setSearchParams(searchParams);
编辑:非数组条目
如果 'searchParams' 不是一个数组,你可以在 searchParams 上调用 Object.keys() 方法,它会返回一个键的数组,然后你可以在该数组上使用 filter() 方法。
const [searchParams, setSearchParams] = useSearchParams();
const keys = ['Title', 'State'];
const filteredParams = Object.keys(searchParams).filter((key) => !keys.includes(key.toLowerCase()));
filteredParams.forEach((key) => searchParams.delete(key));
setSearchParams(searchParams);
英文:
Use .filter() instead. The result of the filter is an array of keys that are not in the keys array (i.e. Title and State).
You should call setSearchParams after the filter is applied, like this:
const [searchParams, setSearchParams] = useSearchParams();
const keys = ['Title', 'State']
const filteredParams = searchParams.filter((key) => !keys.includes(key.toLowerCase()));
filteredParams.forEach((key) => searchParams.delete(key));
setSearchParams(searchParams);
EDIT: Non-array entries
If 'searchParams' is not an array, you can call the Object.keys() method on searchParams which will return an array of keys, then you can use the filter() method on that array.
const [searchParams, setSearchParams] = useSearchParams();
const keys = ['Title', 'State']
const filteredParams = Object.keys(searchParams).filter((key) => !keys.includes(key.toLowerCase()));
filteredParams.forEach((key) => searchParams.delete(key));
setSearchParams(searchParams);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论