Reactjs React-如何从查询字符串中获取参数值?
如何在routes.jsx文件中定义路由,以从Twitter的服务器重定向后通过单一登录过程生成的URL中捕获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
\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)
来探索所有的可能性。这个.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)
在任何情况下都会有帮助。反应路由器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.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'}
这将显示组件中的整个查询字符串(在?
符号之后的所有内容),您需要在其中访问可以使用的参数
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 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))
如果你没有得到这个.props
。。。根据其他答案,您可能需要将与路由器一起使用():
从“React”导入React
从“道具类型”导入道具类型
导入{with
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"
}
function useQueryParams() {
const params = new URLSearchParams(
window ? 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"]