如何在反应路由器 v4中获取查询参数

我在我的项目中使用的是 response-router-dom 4.0.0-beta.6。 我有个准则,比如说:

<Route exact path="/home" component={HomePage}/>

我想得到 HomePage组件中的查询参数。 我已经找到了 location.search参数,它看起来像这样: ?key=value,所以它是未解析的。

使用反应路由器 v4获取查询参数的正确方法是什么?

133240 次浏览

The ability to parse query strings was taken out of V4 because there have been requests over the years to support different implementation. With that, the team decided it would be best for users to decide what that implementation looks like. We recommend importing a query string lib. Here's one that I use

const queryString = require('query-string');


const parsed = queryString.parse(props.location.search);

You can also use new URLSearchParams if you want something native and it works for your needs

const params = new URLSearchParams(props.location.search);
const foo = params.get('foo'); // bar

You can read more about the decision here

The accepted answer works well but if you don't want to install an additional package, you can use this:

getUrlParameter = (name) => {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
let regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
let results = regex.exec(window.location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

Given http://www.google.co.in/?key=value

getUrlParameter('key');

will return value

I was researching about params for react router v4, and they didn't use it for v4, not like react router v2/3. I'll leave another function - maybe somebody will find it helpful. You only need es6 or plain javascript.

function parseQueryParams(query) {
//You get a '?key=asdfghjkl1234567890&val=123&val2&val3=other'
const queryArray = query.split('?')[1].split('&');
let queryParams = {};
for (let i = 0; i < queryArray.length; i++) {
const [key, val] = queryArray[i].split('=');
queryParams[key] = val ? val : true;
}
/* queryParams =
{
key:"asdfghjkl1234567890",
val:"123",
val2:true,
val3:"other"
}
*/
return queryParams;
}

Also, this function can be improved

I just made this so don't need to change the whole code structure(where you use query from redux router store) if you update to react router v4 or higher from a lower version.

https://github.com/saltas888/react-router-query-middleware

The given answer is solid.

If you want to use the qs module instead of query-string (they're about equal in popularity), here is the syntax:

const query = qs.parse(props.location.search, {
ignoreQueryPrefix: true
})

The ignoreQueryPrefix option is to ignore the leading question mark.

Without need of any package:

const params = JSON.parse(JSON.stringify(this.props.match.params));

Then you can reach the related parameters with params.id

Eh?

queryfie(string){
return string
.slice(1)
.split('&')
.map(q => q.split('='))
.reduce((a, c) => { a[c[0]] = c[1]; return a; }, {});
}


queryfie(this.props.location.search);

Another useful approach could be to use the out of the box URLSearchParams like this;

  let { search } = useLocation();


const query = new URLSearchParams(search);
const paramField = query.get('field');
const paramValue = query.get('value');

Clean, readable and doesn't require a module. More info below;

Very easy

just use hook useParams()

Example:

Router:

<Route path="/user/:id" component={UserComponent} />

In your component:

export default function UserComponent() {


const { id } = useParams();


return (
<>{id}</>
);
}

Here is a way without importing any additional libraries

const queryString = (string) => {
return string.slice(1).split('&')
.map((queryParam) => {
let data = queryParam.split('=')
return { key: data[0], value: data[1] }
})
.reduce((query, data) => {
query[data.key] = data.value
return query
}, {});
}


const paramData = (history && history.location && history.location.search)
? parseQueryString(history.location.search)
: null;

According to their docs https://reactrouter.com/web/example/query-parameters you need:

import { useLocation } from 'react-router-dom';


// A custom hook that builds on useLocation to parse
// the query string for you.
function useQuery() {
return new URLSearchParams(useLocation().search);
}


function App() {
const query = useQuery();
console.log(query.get('queryYouAreLookingFor'));
}

React Router v6

Source: Getting Query Strings (Search Params) in React Router

I know this was a question for v4, but with v6 being released, here is how we can search for params in the new version of React Router.

With the new useSearchParams hook and the .get() method:

const Users = () => {
const [searchParams] = useSearchParams();
console.log(searchParams.get('sort')); // 'name'


return <div>Users</div>;
};

With this approach, you can read one or a few params.

Read more and live demo: Getting Query Strings (Search Params) in React Router

If your route definition is like this:

<Route exact path="/edit/:id" ...../>


import { useParams } from "react-router";


const { id } = useParams();


console.log(id)