Reactjs React-如何从查询字符串中获取参数值?

Reactjs React-如何从查询字符串中获取参数值?,reactjs,react-router,Reactjs,React Router,如何在routes.jsx文件中定义路由,以从Twitter的服务器重定向后通过单一登录过程生成的URL中捕获\uu firebase\u request\u key参数值 http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla 我尝试了以下路由配置,但:redirectParam未捕获提到的参数: <Router> <Route path="/" component={M

如何在routes.jsx文件中定义路由,以从Twitter的服务器重定向后通过单一登录过程生成的URL中捕获
\uu firebase\u request\u key
参数值

http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla
我尝试了以下路由配置,但
:redirectParam
未捕获提到的参数:

<Router>
  <Route path="/" component={Main}>
    <Route path="signin" component={SignIn}>
      <Route path=":redirectParam" component={TwitterSsoButton} />
    </Route>
  </Route>
</Router>

此.props.params。您的参数名称将起作用

const authResult = new URLSearchParams(window.location.search); 
const code = authResult.get('code')
这是从查询字符串中获取参数的方法。

请执行
console.log(this.props)探索所有可能性。

反应路由器v4和反应路由器v5,通用

React Router v4不再为您解析查询,但您只能通过
this.props.location.search
(或useLocation,见下文)访问它。原因见

例如,当库作为
qs导入时,您可以

qs.parse(this.props.location.search, { ignoreQueryPrefix: true }).__firebase_request_key
另一个图书馆将是。有关解析搜索字符串的更多信息,请参阅。如果您不需要,也可以使用

new URLSearchParams(this.props.location.search).get("__firebase_request_key")
对于功能组件,您将用钩子替换
this.props.location
。注意,您可以使用
window.location.search
,但这不允许触发对更改的React呈现。 如果您的(非功能性)组件不是
交换机的直接子组件,则需要使用访问路由器提供的任何道具


React路由器v3

React路由器已经为您解析了位置,并将其作为道具传递给您。您可以通过以下方式访问查询(url中的?之后)部分:

如果要查找路径参数值,请在路由器内用冒号(:)分隔,这些值可以通过

this.props.match.params.redirectParam
这适用于最新的React路由器v3版本(不确定是哪个)。据报告,较旧的路由器版本使用了
this.props.params.redirectParam

概述

nizam.sp的建议

console.log(this.props)
在任何情况下都会有帮助。

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

this.props.params.userId

在需要访问可以使用的参数的组件中

this.props.location.state.from.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'}
这将显示整个查询字符串(在
符号之后的所有内容)

React Router v4 使用
组件

<Route path="/users/:id" component={UserPage}/> 
<Route path="/users/:id" render={(props) => <UserPage {...props} />}/> 
组件将使用管线道具自动渲染


使用
渲染

<Route path="/users/:id" component={UserPage}/> 
<Route path="/users/:id" render={(props) => <UserPage {...props} />}/> 

路由道具被传递到渲染函数。

如果您没有获得
此。道具
。。。根据其他答案,您可能需要将
与路由器一起使用
():

从“React”导入React
从“道具类型”导入道具类型
从“react router”导入{withRouter}
//显示当前位置路径名的简单组件
类ShowTheLocation扩展了React.Component{
静态类型={
匹配:PropTypes.object.isRequired,
位置:PropTypes.object.isRequired,
历史记录:PropTypes.object.isRequired
}
render(){
const{match,location,history}=this.props
返回(
您现在位于{location.pathname}
)
}
}
//创建一个与路由器“连接”(借用redux术语)的新组件。
const twittersobutton=带路由器(显示位置)
//这将影响到shouldComponentUpdate
带路由器(连接(…)(MyComponent))
//这是不可能的
连接(…)(使用路由器(MyComponent))

React路由器v4不再具有
对象(请参阅讨论)。因此,被接受的答案将不适用于较新的项目

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'}

如果你的路由器是这样的

<Route exact path="/category/:id" component={ProductList}/>
this.props.match.params.id
<Route path="some/path/:id" .../>
componentDidMount(){
  console.log(this.props);
  console.log(this.props.match.params.id);
}

React路由器v3

使用React Router v3,您可以从
this.props.location.search
(?qs1=naisarg&qs2=parmar)获取查询字符串。例如,使用
let params=queryString.parse(this.props.location.search)
,将给出
{qs1:'naisorg',qs2:'parmar'}


React路由器v4

const urlParams = new URLSearchParams(this.props.location.search)
const key = urlParams.get('__firebase_request_key')
使用React Router v4,不再存在
this.props.location.query
。您需要改用
this.props.location.search
,自己或使用现有包(例如)解析查询参数

示例

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

console.log(params)
下面是使用React Router v4和
查询字符串
库的一个简单示例

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);
Rational

React路由器删除
查询
属性的团队rational是:

有许多流行的软件包执行查询字符串解析/字符串化的方式略有不同,其中的每一种差异对于某些用户来说可能是“正确的”,而对于其他用户来说可能是“不正确的”。如果你选择了“正确的”一个,它只适合某些人。然后,它需要为其他用户添加一种方法,以便在他们首选的查询解析包中进行替换。React Router没有内部使用搜索字符串来解析键值对,因此它不需要选择其中哪一个应该是“正确的”

[……]

4.0采用的方法是去掉所有“包含电池”的功能,回到基本的路由。如果您需要查询字符串解析、异步加载、Redux集成或其他非常特定的功能,那么您可以使用专门针对您的用例的库来添加这些功能。你可以根据自己的喜好和需要定制一些你不需要的东西


您可以在上找到完整的讨论。

React Router v4

const urlParams = new URLSearchParams(this.props.location.search)
const key = urlParams.get('__firebase_request_key')
请注意,它目前是实验性的

在此处检查浏览器兼容性:

在React R中
<Route path="some/path" ..../>
<Route path="some/path/:id" .../>
componentDidMount(){
  console.log(this.props);
  console.log(this.props.match.params.id);
}
export default withRouter(Component);
import { withRouter } from 'react-router-dom'
http://www.google.com.au?token=123
 const query = new URLSearchParams(this.props.location.search);
const token = query.get('token')
console.log(token)//123
npm i query-string
 import queryString from 'query-string'
const value=queryString.parse(this.props.location.search);
const token=value.token;
console.log('token',token)//123
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);
}
getQueryVariable('aid') //160990
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>
  )
}
import { Switch, Route, Link } from "react-router-dom";

<Route path="/profile" exact component={SelectProfile} />
<Route
  path="/profile/:profileId"
  render={props => {
    return <Profile {...props} loading={this.state.loading} />;
  }}
/>
</Switch>
</div>
<Route path="/test/:slug" component={Dashboard} />
http://localhost:3000/test/signin?_k=v9ifuf&__firebase_request_key=blablabla
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>;
}
let city = (new URLSearchParams(window.location.search)).get("city")
const authResult = new URLSearchParams(window.location.search); 
const code = authResult.get('code')
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
}
// current url: http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla
const { __firebase_request_key } = useSearchParams('__firebase_request_key');
// current url: http://localhost:3000/home?b=value
const searchParams = useSearchParameters('a', 'b'); // {a: null, b: 'value'}
<Route path="/posts/:id">
  <BlogPost />
</Route>
const { id } = useParams();
<Route exact path='/' render={props => (
import queryString from 'query-string';
...
const queryStringParams = queryString.parse(window.location.search);
const getQueryParams = (s?: string): Map<string, string> => {
  if (!s || typeof s !== 'string' || s.length < 2) {
    return new Map();
  }

  const a: [string, string][] = s
    .substr(1) // remove `?`
    .split('&') // split by `&`
    .map(x => {
      const a = x.split('=');
      return [a[0], a[1]];
    }); // split by `=`

  return new Map(a);
};
const {useLocation} from 'react-router-dom';
const s = useLocation().search;
const m = getQueryParams(s);
let myVariable = new URLSearchParams(history.location.search).get('business');
>  getQueryParams()
<  {
     a: "1",
     b: "c",
     d: "test"
   }
export default function useQueryParams() {
  const params = new URLSearchParams(window.location.search)

  return new Proxy(params, {
    get(target, prop) {
      return target.get(prop);
    },
  });
}
const { page, fields, count } = useQueryParams();

console.log(params)
const url = new URL(window.location.href);
const yourParamName = url.searchParams.get('yourParamName');
const yourParamName = new URL(window.location.href).searchParams.get('yourParamName')
const params = new URLSearchParams(window.location.search);
const yourParamName = params.get('yourParamName');
const yourParamName = new URLSearchParams(window.location.search).get('yourParamName')
const yourParamName = new URLSearchParams(window.location.search).getAll('yourParamName[]')
["yourParamValue1", "yourParamValue2"]