如何从查询字符串中获取参数值

Fra*_*nco 323 reactjs react-router

如何在routes.jsx文件中定义路由,以便__firebase_request_key从服务器重定向后从Twitter的单点登录进程生成的URL中捕获参数值?

http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下路由配置,但是:redirectParam没有捕获所提到的参数:

<Router>
  <Route path="/" component={Main}>
    <Route path="signin" component={SignIn}>
      <Route path=":redirectParam" component={TwitterSsoButton} />
    </Route>
  </Route>
</Router>
Run Code Online (Sandbox Code Playgroud)

Chr*_*ian 406

反应路由器v3

React Router已经为您解析了该位置,并将其作为道具传递给您的RouteComponent.您可以访问查询(在网址中的?之后)部分

this.props.location.query.__firebase_request_key
Run Code Online (Sandbox Code Playgroud)

如果您正在寻找路径参数值,在路由器内部用冒号(:)分隔,可以通过这些访问

this.props.match.params.redirectParam
Run Code Online (Sandbox Code Playgroud)

这适用于后期React Router v3版本(不确定哪个版本).据报道旧的路由器版本使用this.props.params.redirectParam.

反应路由器v4

React Router v4不再为您解析查询,但您只能通过它访问它this.props.location.search.有理由看nbeuchat的回答.

例如,您可以执行导入的查询字符串qs

qs.parse(this.props.location.search, { ignoreQueryPrefix: true }).__firebase_request_key
Run Code Online (Sandbox Code Playgroud)

此外,如果您的组件不是a的直接子组件,则Switch需要使用withRouter访问任何路由器提供的道具.

一般

nizam.sp的建议

console.log(this.props)
Run Code Online (Sandbox Code Playgroud)

在任何情况下都会有所帮助.

  • 不需要为其更改反应路由器。 (3认同)
  • 在`react-router-dom`中,我不得不使用`withRouter`来完成这项工作! (3认同)
  • 由于 [警告说明](https://developer.mozilla.org/en-US/docs/Web/API/Console/dir),我不建议使用 `console.dir()` ...至少: ) (2认同)
  • @Christian 我最终只使用了普通的 javascript。const path = window.location.pathname; 给我网址。然后我可以按照我需要的方式解析它。我把它放在我的 React 组件的 componentWillMount 生命周期事件中。 (2认同)

spe*_*.sm 156

反应路由器v4

运用 component

<Route path="/users/:id" component={UserPage}/> 
Run Code Online (Sandbox Code Playgroud)

this.props.match.params.id
Run Code Online (Sandbox Code Playgroud)

使用路径道具自动渲染组件.


运用 render

<Route path="/users/:id" render={(props) => <UserPage {...props} />}/> 
Run Code Online (Sandbox Code Playgroud)

this.props.match.params.id
Run Code Online (Sandbox Code Playgroud)

路径道具传递给渲染功能.

  • 不幸的是,这并没有回答这个问题,因为你不一定会有`/ users /?q = ...`但是你可以拥有`/ user?q = ...`.你应该在React Router v4中使用`this.props.location.search`并自己解析结果,如下面的答案所述. (26认同)
  • 我在使用 React Router v4 访问子组件中应用程序当前 URL 的“查询参数”时遇到了类似的问题。如果您正在寻找“查询参数”,React Router 4 中的 this.props.location.query 已被删除(当前使用 v4.1.1)。请参阅此答案:/sf/answers/3054159391/ (2认同)

nbe*_*hat 95

反应路由器v4

使用React Router v4,this.props.location.search它不再存在.您需要使用let params = queryString.parse(this.props.location.search)而不是自己解析查询参数或使用现有的包来解析查询参数{ qs1 : 'naisarg', qs2 : 'parmar'}.

这是使用React Router v4和this.props.location.query库的最小示例.

import { withRouter } from 'react-router-dom';
import queryString from 'query-string';

class ActivateAccount extends Component{
    someFunction(){
        let params = queryString.parse(this.props.location.search)
        ...
    }
    ...
}
export default withRouter(ActivateAccount);
Run Code Online (Sandbox Code Playgroud)

合理的

React Router的团队合理删除this.props.location.search属性是:

有许多流行的包对查询字符串解析/字符串化略有不同,并且这些差异中的每一个对于某些用户可能是"正确的"方式而对于其他用户可能是"不正确的".如果React Router选择了"正确的",它只适合某些人.然后,它需要为其他用户添加一种替代其首选查询解析包的方法.React Router没有内部使用搜索字符串来要求它解析键值对,所以它不需要选择其中哪一个应该是"正确的".

[...]

4.0采用的方法是去除所有"包含电池"的功能,并回到基本路由.如果您需要查询字符串解析或异步加载或Redux集成或其他非常具体的内容,那么您可以使用专门针对您的用例的库添加它.您不需要的东西很少,您可以根据自己的喜好和需求定制东西.

你可以在GitHub上找到完整的讨论.

  • @SuperUberDuper,因为Edge和iOS Safari - https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams#Browser_compatibility (3认同)
  • 当然可以,但是只需使用 URLSearchParams polyfill (3认同)
  • 为什么可以使用URLSearchParams甚至需要lib (2认同)

小智 63

使用 React 钩子时,无法访问this.props.location. 要捕获 url 参数,请使用windowobject。

const search = window.location.search;
const params = new URLSearchParams(search);
const foo = params.get('bar');
Run Code Online (Sandbox Code Playgroud)

  • IE 支持基本上无关紧要,因为 Microsoft 不再支持 IE 11。IE 占所有桌面浏览器的比例不到 0.5%:https://www.lambdatest.com/web-technologies/urlsearchparams-support-on-ie-11 您可以非常自由地使用“URLSearchParams” (2认同)

JTG*_*JTG 58

React Router v4不再具有该 props.location.query 对象(参见github讨论).因此,接受的答案不适用于较新的项目.

v4的解决方案是使用外部库查询字符串来解析props.location.search

const qs = require('query-string');
//or
import * as qs from 'query-string';

console.log(location.search);
//=> '?foo=bar'

const parsed = qs.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}
Run Code Online (Sandbox Code Playgroud)

  • 出于某种原因,我 qs.parse 的结果是:`{'?foo': 'bar'}` (4认同)
  • @Chris`var prefixed = qs.parse('?a = b&c = d',{ignoreQueryPrefix:true});`应该修复它.在此处找到示例:https://github.com/ljharb/qs (2认同)

dsg*_*fin 46

反应路由器 5.1+

5.1推出各种钩子状useLocation,并useParams可能是使用在这里。

例子:

<Route path="/test/:slug" component={Dashboard} />
Run Code Online (Sandbox Code Playgroud)

那么如果我们访问了说

http://localhost:3000/test/signin?_k=v9ifuf&__firebase_request_key=blablabla
Run Code Online (Sandbox Code Playgroud)

你可以像这样检索它

import { useLocation } from 'react-router';
import queryString from 'query-string';

const Dashboard: React.FC = React.memo((props) => {
    const location = useLocation();

    console.log(queryString.parse(location.search));

    // {__firebase_request_key: "blablabla", _k: "v9ifuf"}

    ...

    return <p>Example</p>;
}
Run Code Online (Sandbox Code Playgroud)


MIN*_* WU 42

据我所知,有三种方法可以做到.

1.使用正则表达式获取查询字符串.

2.您可以使用浏览器API.image当前网址是这样的:

http://www.google.com.au?token=123
Run Code Online (Sandbox Code Playgroud)

我们只想得到123;

第一

 const query = new URLSearchParams(this.props.location.search);
Run Code Online (Sandbox Code Playgroud)

然后

const token = query.get('token')
console.log(token)//123
Run Code Online (Sandbox Code Playgroud)

3.使用名为'query-string'的第三个库.首先安装它

npm i query-string
Run Code Online (Sandbox Code Playgroud)

然后将其导入当前的javascript文件:

 import queryString from 'query-string'
Run Code Online (Sandbox Code Playgroud)

下一步是在当前网址中获取"令牌",请执行以下操作:

const value=queryString.parse(this.props.location.search);
const token=value.token;
console.log('token',token)//123
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.

更新于25/02/2019

  1. 如果当前网址如下所示:

http://www.google.com.au?app=home&act=article&aid=160990

我们定义一个函数来获取参数:

function getQueryVariable(variable)
{
        var query = window.location.search.substring(1);
        console.log(query)//"app=article&act=news_content&aid=160990"
        var vars = query.split("&");
        console.log(vars) //[ 'app=article', 'act=news_content', 'aid=160990' ]
        for (var i=0;i<vars.length;i++) {
                    var pair = vars[i].split("=");
                    console.log(pair)//[ 'app', 'article' ][ 'act', 'news_content' ][ 'aid', '160990' ] 
        if(pair[0] == variable){return pair[1];}
         }
         return(false);
}
Run Code Online (Sandbox Code Playgroud)

我们可以通过以下方式获得"援助"

getQueryVariable('aid') //160990
Run Code Online (Sandbox Code Playgroud)

  • IE 不支持 URLSearchParams(如果这与任何人相关:) (2认同)

Hun*_*ter 35

使用这种单行代码,您可以在 React Hook 和 React Class Component 中的任何地方使用纯 JavaScript 使用它。

https://www.hunterisgod.com/?city=莱比锡

let city = (new URLSearchParams(window.location.search)).get("city")
Run Code Online (Sandbox Code Playgroud)


Tom*_*ike 23

您可以检查 react-router,简单来说,只要您在路由器中定义,就可以使用代码获取查询参数:

this.props.params.userId
Run Code Online (Sandbox Code Playgroud)

  • 这不是OP的*右*答案.`props.params`用于URL参数(在反应路由器中以前缀为':'的url段),`props.location.query`存储查询字符串参数(在'?'之后)并且是OP想要的. (23认同)

小智 19

反应路由器v4

const urlParams = new URLSearchParams(this.props.location.search)
const key = urlParams.get('__firebase_request_key')
Run Code Online (Sandbox Code Playgroud)

请注意,它目前是实验性的.

在此处检查浏览器兼容性:https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams#Browser_compatibility

  • 不错的解决方案,但不幸的是 IE 不支持 (( (3认同)

小智 15

如果您的路由器是这样的

<Route exact path="/category/:id" component={ProductList}/>
Run Code Online (Sandbox Code Playgroud)

你会得到这样的id

this.props.match.params.id
Run Code Online (Sandbox Code Playgroud)

  • @ MarkA.Tagliaferro该道具仅可用于由路线渲染的组件。如果不是您的组件,则可以通过将组件包装在withRouter HOC中来访问它们。 (2认同)

小智 14

说有一个网址如下

http://localhost:3000/callback?code=6c3c9b39-de2f-3bf4-a542-3e77a64d3341

如果我们想从该 URL 中提取代码,下面的方法将起作用。

const authResult = new URLSearchParams(window.location.search); 
const code = authResult.get('code')
Run Code Online (Sandbox Code Playgroud)


Naz*_*iks 13

不是反应方式,但我相信这个单行功能可以帮助你:)

const getQueryParams = () => window.location.search.replace('?', '').split('&').reduce((r,e) => (r[e.split('=')[0]] = decodeURIComponent(e.split('=')[1]), r), {});
Run Code Online (Sandbox Code Playgroud)

示例:
URL:  ...?a=1&b=c&d=test
代码:  

>  getQueryParams()
<  {
     a: "1",
     b: "c",
     d: "test"
   }
Run Code Online (Sandbox Code Playgroud)


GMK*_*ain 13

尝试这个

ReactJS

http://localhost:4000/#/amoos?id=101

// ReactJS
import React from "react";
import { useLocation } from "react-router-dom";

const MyComponent = () => {
    const search = useLocation().search;
    const id = new URLSearchParams(search).get("id");
    console.log(id); //101
}
Run Code Online (Sandbox Code Playgroud)

// VanillsJS
const url = "http://localhost:4000/#/amoos?id=101"  // We can use 'window.location'

function getQuery(url, q) {
   return (url.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1];
}

console.log(getQuery(url, "id"))
Run Code Online (Sandbox Code Playgroud)


jer*_*naa 12

无需第 3 方库或复杂的解决方案即可在一行中完成所有操作。这是如何

let myVariable = new URLSearchParams(history.location.search).get('business');
Run Code Online (Sandbox Code Playgroud)

您唯一需要更改的是带有您自己的参数名称的“业务”一词。

示例 url.com?business=hello

myVariable 的结果将是 hello

  • `history.location.search` 在我的情况下不起作用,而不是我使用 `window.location.search` 并且它的工作完美。`new URLSearchParams(window.location.search).get('business')` (3认同)

Bar*_*osz 8

React Router v5.1引入了钩子:

为了

<Route path="/posts/:id">
  <BlogPost />
</Route>
Run Code Online (Sandbox Code Playgroud)

您可以使用钩子访问 params / id :

const { id } = useParams();
Run Code Online (Sandbox Code Playgroud)

更多在这里


Yas*_*kar 8

function useQueryParams() {
    const params = new URLSearchParams(
      window ? window.location.search : {}
    );

    return new Proxy(params, {
        get(target, prop) {
            return target.get(prop)
        },
    });
}

Run Code Online (Sandbox Code Playgroud)

React hooks 很棒

如果您的网址看起来像/users?page=2&count=10&fields=name,email,phone

const { page, fields, count } = useQueryParams();

console.log(params)
Run Code Online (Sandbox Code Playgroud)


and*_*ras 8

您可以使用以下反应钩子:

  1. 如果 url 发生变化,钩子状态就会更新
  2. SSR: typeof window === "undefined",只是检查window导致错误(尝试一下)
  3. Proxy对象隐藏实现,因此undefined返回而不是null

这是将搜索参数作为对象获取的函数:

const getSearchParams = <T extends object>(): Partial<T> => {
    // server side rendering
    if (typeof window === "undefined") {
        return {}
    }

    const params = new URLSearchParams(window.location.search) 

    return new Proxy(params, {
        get(target, prop, receiver) {
            return target.get(prop as string) || undefined
        },
    }) as T
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它作为钩子:

const useSearchParams = <T extends object = any>(): Partial<T> => {
    const [searchParams, setSearchParams] = useState(getSearchParams())

    useEffect(() => {
        setSearchParams(getSearchParams())
    }, [typeof window === "undefined" ? "once" : window.location.search])

    return searchParams
}

Run Code Online (Sandbox Code Playgroud)

如果您的网址如下所示:

/app?page=2&count=10

你可以这样读:

const { page, count } = useQueryParams();

console.log(page, count)
Run Code Online (Sandbox Code Playgroud)


Chi*_*hor 8

反应路由器 v6

\n

来源:在 React Router 中获取查询字符串(搜索参数)

\n

使用新的useSearchParams钩子和.get()方法:

\n
const Users = () => {\n  const [searchParams] = useSearchParams();\n  console.log(searchParams.get(\'sort\')); // \'name\'\n\n  return <div>Users</div>;\n};\n
Run Code Online (Sandbox Code Playgroud)\n

通过这种方法,您可以读取一个或几个参数。

\n

BONUS 将参数作为对象获取:

\n

如果您需要一次获取所有查询字符串参数,那么我们可以Object.fromEntries这样使用:

\n
const Users = () => {\n  const [searchParams] = useSearchParams();\n  console.log(Object.fromEntries([...searchParams])); // \xe2\x96\xb6 { sort: \'name\', order: \'asecnding\' }\n  return <div>Users</div>;\n};\n
Run Code Online (Sandbox Code Playgroud)\n

阅读更多内容和现场演示:在 React Router 中获取查询字符串(搜索参数)

\n

  • 每个人都应该支持这个解决方案!:) (3认同)

Shu*_*tri 7

React router从v4开始,不再query params直接在其location对象中提供.原因是

有许多流行的包对查询字符串解析/字符串化略有不同,并且这些差异中的每一个对于某些用户可能是"正确的"方式而对于其他用户可能是"不正确的".如果React Router选择了"正确的",它只适合某些人.然后,它需要为其他用户添加一种替代其首选查询解析包的方法.React Router没有内部使用搜索字符串来要求它解析键值对,所以它不需要选择其中哪一个应该是"正确的".

包含它之后,只需在您的视图组件中解析期望查询对象的location.search就更有意义了.

你可以通过覆盖withRouterfrom react-routerlike 来做到这一点

customWithRouter.js

import { compose, withPropsOnChange } from 'recompose';
import { withRouter } from 'react-router';
import queryString from 'query-string';

const propsWithQuery = withPropsOnChange(
    ['location', 'match'],
    ({ location, match }) => {
        return {
            location: {
                ...location,
                query: queryString.parse(location.search)
            },
            match
        };
    }
);

export default compose(withRouter, propsWithQuery)
Run Code Online (Sandbox Code Playgroud)


Rud*_*ynh 7

也许有点晚了,但是这个 react hook 可以帮助您在 URL 查询中获取/设置值:https : //github.com/rudyhuynh/use-url-search-params(由我编写)。

无论有没有react-router. 以下是您的案例中的代码示例:

import React from "react";
import { useUrlSearchParams } from "use-url-search-params";

const MyComponent = () => {
  const [params, setParams] = useUrlSearchParams()
  return (
    <div>
      __firebase_request_key: {params.__firebase_request_key}
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)


Has*_*eed 7

http://localhost:8000/#/signin?id=12345

import React from "react";
import { useLocation } from "react-router-dom";

const MyComponent = () => {
  const search = useLocation().search;
const id=new URLSearchParams(search).get("id");
console.log(id);//12345
}
Run Code Online (Sandbox Code Playgroud)


jtl*_*sey 6

如果你没有得到this.props...你期望基于其他答案,你可能需要使用withRouter(docs v4):

import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (
      <div>You are now at {location.pathname}</div>
    )
  }
}

// Create a new component that is "connected" (to borrow redux terminology) to the router.  
const TwitterSsoButton = withRouter(ShowTheLocation)  

// This gets around shouldComponentUpdate
withRouter(connect(...)(MyComponent))

// This does not
connect(...)(withRouter(MyComponent))
Run Code Online (Sandbox Code Playgroud)


niz*_*.sp 5

this.props.params.your_param_name 将工作.

这是从查询字符串中获取参数的方法.
请尽力console.log(this.props);探索所有可能性.


小智 5

componentDidMount(){
    //http://localhost:3000/service/anas
    //<Route path="/service/:serviceName" component={Service} />
    const {params} =this.props.match;
    this.setState({ 
        title: params.serviceName ,
        content: data.Content
    })
}
Run Code Online (Sandbox Code Playgroud)

  • 欢迎使用堆栈溢出!请不要只用源代码来回答。尝试提供有关您的解决方案如何工作的很好的描述。请参阅:[如何写出好的答案?](https://stackoverflow.com/help/how-to-answer)。谢谢 (4认同)

小智 5

我很难解决这个问题.如果没有上述工作,您可以尝试这样做.我正在使用create-react-app

要求

react-router-dom":"^ 4.3.1"

在指定路由器的位置

<Route path="some/path" ..../>
Run Code Online (Sandbox Code Playgroud)

像这样添加您想要传入的参数名称

<Route path="some/path/:id" .../>
Run Code Online (Sandbox Code Playgroud)

在您渲染某些/ path的页面上,您可以指定此参数来查看参数名称调用ID,如下所示

componentDidMount(){
  console.log(this.props);
  console.log(this.props.match.params.id);
}
Run Code Online (Sandbox Code Playgroud)

在您导出默认值的末尾

export default withRouter(Component);
Run Code Online (Sandbox Code Playgroud)

请记住包含导入

import { withRouter } from 'react-router-dom'
Run Code Online (Sandbox Code Playgroud)

当console.log(this.props)你将能够传递下来的东西.玩得开心!

  • 如果使用 TypeScript 不要忘记添加 `RouteComponentProps&lt;{id: number}&gt;` (2认同)
  • 在哪里添加 RouteComponentProps&lt;{id: number}&gt; ? (2认同)

kaj*_*kal 5

您可以创建简单的钩子来从当前位置提取搜索参数:

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

export function useSearchParams<ParamNames extends string[]>(...parameterNames: ParamNames): Record<ParamNames[number], string | null> {
    const { search } = useLocation();
    return React.useMemo(() => { // recalculate only when 'search' or arguments changed
        const searchParams = new URLSearchParams(search);
        return parameterNames.reduce((accumulator, parameterName: ParamNames[number]) => {
            accumulator[ parameterName ] = searchParams.get(parameterName);
            return accumulator;
        }, {} as Record<ParamNames[number], string | null>);
    }, [ search, parameterNames.join(',') ]); // join for sake of reducing array of strings to simple, comparable string
}
Run Code Online (Sandbox Code Playgroud)

那么你可以像这样在你的功能组件中使用它:

// current url: http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla
const { __firebase_request_key } = useSearchParams('__firebase_request_key');
Run Code Online (Sandbox Code Playgroud)
// current url: http://localhost:3000/home?b=value
const searchParams = useSearchParameters('a', 'b'); // {a: null, b: 'value'}
Run Code Online (Sandbox Code Playgroud)


sig*_*i13 5

也许有人可以帮助澄清原因,但如果您尝试点击 props 从 App.js 页面上全新安装的 Create React App 中查找位置,您会得到:

类型错误:无法读取未定义的属性“搜索”

即使我有 App.js 作为主路由:

<Route exact path='/' render={props => (
Run Code Online (Sandbox Code Playgroud)

仅在 App.js 上,使用 window.location 对我有用:

import queryString from 'query-string';
...
const queryStringParams = queryString.parse(window.location.search);
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用。如果对否决票有任何澄清,我们将不胜感激 (4认同)

小智 5

实际上没有必要使用 3rd 方库。我们可以用纯 JavaScript 来制作。

考虑以下 URL:

https://example.com?yourParamName=yourParamValue

现在我们得到:

const url = new URL(window.location.href);
const yourParamName = url.searchParams.get('yourParamName');
Run Code Online (Sandbox Code Playgroud)

简而言之

const yourParamName = new URL(window.location.href).searchParams.get('yourParamName')
Run Code Online (Sandbox Code Playgroud)

另一个智能解决方案(推荐)

const params = new URLSearchParams(window.location.search);
const yourParamName = params.get('yourParamName');
Run Code Online (Sandbox Code Playgroud)

简而言之

const yourParamName = new URLSearchParams(window.location.search).get('yourParamName')
Run Code Online (Sandbox Code Playgroud)

笔记:

对于具有多个值的参数,使用“getAll”而不是“get”

https://example.com?yourParamName[]=yourParamValue1&yourParamName[]=yourParamValue2

const yourParamName = new URLSearchParams(window.location.search).getAll('yourParamName[]')
Run Code Online (Sandbox Code Playgroud)

结果将是这样的:

["yourParamValue1", "yourParamValue2"]
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

463406 次

最近记录:

5 年,11 月 前