问题描述
我想像这样在React js中解析网址中的查询:
const location = useHistory().location;
const parsed = parse(location,true);
console.log(parsed);
但是控制台给了我这个:
host: "localhost:3000"
hostname: "localhost"
href: "http://localhost:3000/[object Object]"
origin: "http://localhost:3000"
password: ""
pathname: "/[object Object]"
port: "3000"
protocol: "http:"
query: {}
slashes: true
查询对象为空,我需要一个并且路径名不可用。 如何使用url-parse包正确解析react js中url中的查询?
解决方法
我认为您使用了错误的反应挂钩。 useHistory
挂钩用于程序化导航。要访问位置对象,请使用useLocation
。
const location = useLocation();
const parsed = parse(location.search,true);
,
使用查询字符串包解决了该问题。
import queryString from 'query-string';
const location = useHistory().location;
const query = queryString.parse(location.search); // returns the query object