React路由器Dom V6
https://reactrouter.com/docs/en/v6/hooks/use-search-params
import * as React from "react";
import { useSearchParams } from "react-router-dom";
function App() {
let [searchParams, setSearchParams] = useSearchParams();
function handleSubmit(event) {
event.preventDefault();
// The serialize function here would be responsible for
// creating an object of { key: value } pairs from the
// fields in the form that make up the query.
let params = serializeFormQuery(event.target);
setSearchParams(params);
}
return (
<div>
<form onSubmit={handleSubmit}>{/* ... */}</form>
</div>
);
}
直到React路由器Dom V5
function useQueryParams() {
const params = new URLSearchParams(
window ? window.location.search : {}
);
return new Proxy(params, {
get(target, prop) {
return target.get(prop)
},
});
}
React钩子很棒
如果你的url看起来像/users?页面= 2数= 10字段=姓名、电子邮件、电话
// app.domain.com/users?page=2&count=10&fields=name,email,phone
const { page, fields, count, ...unknown } = useQueryParams();
console.log({ page, fields, count })
console.log({ unknown })
如果您的查询参数包含hyphone("-")或空格(" ")
然后你不能像{page, fields, count,…未知的}
你需要做传统的作业,比如
// app.domain.com/users?utm-source=stackOverFlow
const params = useQueryParams();
console.log(params['utm-source']);