我试图按照React Router Dom文档在版本6中获取URL中的查询参数,方式如下:
import * as React from "react";
import { useSearchParams } from "react-router-dom";
function App() {
let [searchParams, setSearchParams] = useSearchParams();
function handleSubmit(event) {
event.preventDefault();
let params = serializeFormQuery(event.target);
setSearchParams(params);
}
return (
<div>
<form onSubmit={handleSubmit}>{/* ... */}</form>
</div>
);
}
但是它返回了一个空对象
我尝试了其他方法,如下:
import React from "react";
import ReactDOM from "react-dom";
import { Link, useLocation, BrowserRouter as Router } from "react-router-dom";
function User({ name }) {
return <div>{name}</div>;
}
function useQuery() {
return new URLSearchParams(useLocation().search);
}
function useQuerym2() {
const { search } = useLocation();
return React.useMemo(() => new URLSearchParams(search), [search]);
}
function QueryScreen() {
let query = useQuery();
let querym2 = useQuerym2();
return <></>
}
但是得到了相同的结果
最终,我开发了一种从URL中获取查询参数的方法
const convertQueryParamsStringToQueryParamsObject = (string) => {
let queryParams = {};
// remove first letter from query string
string = string.substring(1);
// console.log("string", string);
// convert string to array
const queryParamsArray = string.split("&");
// console.log("queryParamsArray", queryParamsArray);
// covert each index query to object
queryParamsArray.forEach((queryParam) => {
// console.log("queryParam", queryParam);
// split param by =
const queryParamArray = queryParam.split("=");
// console.log("queryParamArray", queryParamArray);
queryParams[queryParamArray[0]] = queryParamArray[1];
// console.log("queryParams", queryParams);
});
return queryParams;
};
您需要在React函数组件中调用它,例如:
const FunchionalComponent =()=> {
const { search } = useLocation();
let queryParams = convertQueryParamsStringToQueryParamsObject(search);
console.log("queryParams", queryParams);
return <></>;
};
react-router-dom@6
的方法。第二个方法/示例是react-router-dom@5
的方法。第三个似乎是某种自制实现。这里确切的问题是什么?有什么问题吗?你所说的“但它返回了一个空对象”是什么意思?究竟返回了什么,并在哪里,你期望得到什么?这篇文章需要一些改进。 - Drew Reese