[英]How to get rid of a query string
SOLVED解决了
I have a kinda stupid issue.我有一个有点愚蠢的问题。 I can't get rid of the query string,.我无法摆脱查询字符串。 Once I put it into the history, I can't find how to remove it.一旦我将它放入历史记录,我就找不到如何删除它。
I have a React app with navigation (Universal Router).我有一个带有导航功能的 React 应用程序(通用路由器)。 I don't believe it is related to the library I use, but rather to a bad use of the URL and History API.我不认为它与我使用的库有关,而是与 URL 和历史记录 API 的错误使用有关。
I have a list of users, and each has a number.我有一个用户列表,每个用户都有一个编号。 I have an input form to enter the number.我有一个输入表格来输入号码。 I append this as a query string in the form /users?nb=1
.我将 append 作为/users?nb=1
形式的查询字符串。 This url is submitted to a resolver that searches in an array of paths.这个 url 被提交给一个在路径数组中搜索的解析器。 The action code corresponding to the /users
path has a function that reads if a query string is present.与/users
路径对应的操作代码有一个 function,它读取是否存在查询字符串。 If yes, extract the number and push the new path /users/1
.如果是,提取号码并推送新路径/users/1
。 This almost works: I push in fact /users/1?nb=1
..这几乎可行:我实际上推/users/1?nb=1
..
Note: I can of course directly push /users/1
without a query string but this is an exercise.注意:我当然可以直接推送/users/1
而无需查询字符串,但这是一个练习。
What is the trick??有什么诀窍?? [EDIT]: override the key search:""
[编辑]:覆盖键search:""
EDIT: https://codesandbox.io/s/universal-router-mobx-demo-jg3um?file=/src/NavBar.js编辑: https://codesandbox.io/s/universal-router-mobx-demo-jg3um?file=/src/NavBar.js
1- the emitting function, creates the query string 1- 发出 function,创建查询字符串
function handleSubmit(e) {
e.preventDefault();
let query = Object.fromEntries(new FormData(e.currentTarget));
const {pathname, search} = window.location
const qstring = new URLSearchParams(search);
for (const k in query){ qstring.append(k, query[k])};
history.push({ pathname, search: "?" + qstring });
}
1b - vs a "normal" link 1b - 与“正常”链接相比
const handleClick = (e) => {
e.preventDefault();
history.push({ pathname: e.target.pathname });
};
2- the conditional path (for the query string) 2- 条件路径(用于查询字符串)
const searchString = new URLSearchParams(window.location.search);
const id = searchString.get("nb");
if (id) { return { redirect: `/users/${id}` } }
3- the resolving 3-解决
const page = await router.resolve({ pathname: location.pathname });
if (page.redirect) {
return history.push({ pathname: page.redirect, search: "" });
} ^^^!
return render(<React.StrictMode>{page}</React.StrictMode>, root);
The pb is solved by adding search:"" which removes the trailing query string. pb 通过添加search:""来解决,它删除了尾随的查询字符串。
So as @Ouroborus showed, you just need to add search:''
in the returned url from the resolver to override the previous query string:因此,正如@Ouroborus 所示,您只需要在解析器返回的 url 中添加search:''
即可覆盖之前的查询字符串:
history.push({pathname: page.redirect, search:""})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.