如何在 react-router v4 中解析查询字符串
How to parse query string in react-router v4
在 react-router v3 中,我可以使用 props.location.query.foo
访问它(如果当前位置是 ?foo=bar
)
在react-router-dom@4.0.0
中props.location
只有props.location.search
和?foo=bar&other=thing
.
这样的字符串
也许我需要手动解析和解构该字符串以找到 foo
或 other
的值。
console.log(this.props)
的截图:
(注意如何从 ?artist=band
在这里我想从 artist
中获取值,即值 band
)
看来你已经猜对了。解析查询字符串的能力已从 V4 中删除,因为多年来一直要求支持不同的实现。有了这个,团队决定最好由用户来决定该实现的样子。我们建议导入查询字符串库。到目前为止,one you mentioned 对我来说效果很好。
const queryString = require('query-string');
const parsed = queryString.parse(props.location.search);
如果你想要原生的东西并且它能满足你的需要,你也可以使用 new URLSearchParams
const search = props.location.search; // could be '?foo=bar'
const params = new URLSearchParams(search);
const foo = params.get('foo'); // bar
您可以阅读有关该决定的更多信息here
很高兴我找到了这个 post。感谢您提供的链接,几个小时后我终于升级了我的代码。
对于那些使用查询字符串的人,您可能需要做类似
的事情
var nameYouWant = queryString.parse(this.props.location.search).nameYouWant;
这种情况发生在我身上,this.props.location.search.theUrlYouWant
会拒绝工作。 Tyler 提到的第二个选项通过一些类似的调整也对我有用。
使用 query-string 模块创建优化的生产版本时,您可能会遇到以下错误。
Failed to minify the code from this file:
./node_modules/query-string/index.js:8
为了克服这个问题,请使用名为 stringquery 的替代模块,它可以在 运行 构建时很好地完成相同的过程,没有任何问题。
import querySearch from "stringquery";
var query = querySearch(this.props.location.search);
谢谢。
我提供我的小 ES6
形状函数,很棒,重量轻且有用:
getQueryStringParams = query => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split('&')
.reduce((params, param) => {
let [key, value] = param.split('=');
params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
return params;
}, {}
)
: {}
};
东西都在这里了,希望对你有帮助。
使用第三方包对于简单的解决方案来说是矫枉过正
componentDidMount() {
const query = new URLSearchParams(
this.props.location.search
);
let data= {};
for (let params of query.entries()) {
data[params[0]] = +params[1];
}
this.setState({ urldata: data});
}
这将简单地将 URL 数据转换为对象。
您可以使用一个简单的函数来提取查询参数,而不是安装包。
//Param Extractor
const parseParams = (params = "") => {
const rawParams = params.replace("?", "").split("&");
const extractedParams = {};
rawParams.forEach((item) => {
item = item.split("=");
extractedParams[item[0]] = item[1];
});
return extractedParams;
};
//Usage
const params = parseParams(this.props?.location?.search); // returns an object like:
// {id:1,name:john...}
我很惊讶没有人提到 UrlSearchParams 和 .get
方法。
使用 React 路由器获取查询字符串的延迟回答 useLocation:
import useLocation from 'react-router';
import queryString from 'query-string';
const handleQueryString = useLocation().search;
// nice=day&very=sunny
// Get a param
const { nice } = queryString.parse(useLocation().search)
use useSearchParams instead of location.search in react-router-v6
import { useSearchParams } from 'react-router-dom';
const Chat = ({location}) => {
const [searchParams] = useSearchParams();
// pass searchParams as a dependency into the useEffect
useEffect(()=>{
const currentParams = Object.fromEntries([...searchParams])
console.log(currentParams);
},[searchParams])
在 react-router v3 中,我可以使用 props.location.query.foo
访问它(如果当前位置是 ?foo=bar
)
在react-router-dom@4.0.0
中props.location
只有props.location.search
和?foo=bar&other=thing
.
也许我需要手动解析和解构该字符串以找到 foo
或 other
的值。
console.log(this.props)
的截图:
?artist=band
在这里我想从 artist
中获取值,即值 band
)
看来你已经猜对了。解析查询字符串的能力已从 V4 中删除,因为多年来一直要求支持不同的实现。有了这个,团队决定最好由用户来决定该实现的样子。我们建议导入查询字符串库。到目前为止,one you mentioned 对我来说效果很好。
const queryString = require('query-string');
const parsed = queryString.parse(props.location.search);
如果你想要原生的东西并且它能满足你的需要,你也可以使用 new URLSearchParams
const search = props.location.search; // could be '?foo=bar'
const params = new URLSearchParams(search);
const foo = params.get('foo'); // bar
您可以阅读有关该决定的更多信息here
很高兴我找到了这个 post。感谢您提供的链接,几个小时后我终于升级了我的代码。
对于那些使用查询字符串的人,您可能需要做类似
的事情var nameYouWant = queryString.parse(this.props.location.search).nameYouWant;
这种情况发生在我身上,this.props.location.search.theUrlYouWant
会拒绝工作。 Tyler 提到的第二个选项通过一些类似的调整也对我有用。
使用 query-string 模块创建优化的生产版本时,您可能会遇到以下错误。
Failed to minify the code from this file: ./node_modules/query-string/index.js:8
为了克服这个问题,请使用名为 stringquery 的替代模块,它可以在 运行 构建时很好地完成相同的过程,没有任何问题。
import querySearch from "stringquery";
var query = querySearch(this.props.location.search);
谢谢。
我提供我的小 ES6
形状函数,很棒,重量轻且有用:
getQueryStringParams = query => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split('&')
.reduce((params, param) => {
let [key, value] = param.split('=');
params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
return params;
}, {}
)
: {}
};
东西都在这里了,希望对你有帮助。
使用第三方包对于简单的解决方案来说是矫枉过正
componentDidMount() {
const query = new URLSearchParams(
this.props.location.search
);
let data= {};
for (let params of query.entries()) {
data[params[0]] = +params[1];
}
this.setState({ urldata: data});
}
这将简单地将 URL 数据转换为对象。
您可以使用一个简单的函数来提取查询参数,而不是安装包。
//Param Extractor
const parseParams = (params = "") => {
const rawParams = params.replace("?", "").split("&");
const extractedParams = {};
rawParams.forEach((item) => {
item = item.split("=");
extractedParams[item[0]] = item[1];
});
return extractedParams;
};
//Usage
const params = parseParams(this.props?.location?.search); // returns an object like:
// {id:1,name:john...}
我很惊讶没有人提到 UrlSearchParams 和 .get
方法。
使用 React 路由器获取查询字符串的延迟回答 useLocation:
import useLocation from 'react-router';
import queryString from 'query-string';
const handleQueryString = useLocation().search;
// nice=day&very=sunny
// Get a param
const { nice } = queryString.parse(useLocation().search)
use useSearchParams instead of location.search in react-router-v6
import { useSearchParams } from 'react-router-dom';
const Chat = ({location}) => {
const [searchParams] = useSearchParams();
// pass searchParams as a dependency into the useEffect
useEffect(()=>{
const currentParams = Object.fromEntries([...searchParams])
console.log(currentParams);
},[searchParams])