如何在我的路由中定义路由。jsx文件捕获__firebase_request_key参数值从一个URL生成的Twitter的单点登录过程后,从他们的服务器重定向?
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>
在typescript中,参见下面的示例片段:
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);
};
在react中使用react-router-dom,你可以做
const {useLocation} from 'react-router-dom';
const s = useLocation().search;
const m = getQueryParams(s);
参见下面的例子
//下面是上面转换和缩小的ts函数
如果(const getQueryParams = t = > {! t | |“字符串”!=typeof t||t.length<2)return new Map;const r=t.substr(1).split("&")。地图(t = > {const r = t.split(" = ");返回[r[0],[1]]});返回新地图(r)};
//一个示例查询字符串
Const s = '?__arg1 = value1&arg2 = value2 '
getQueryParams(s)
console.log (m.get (__arg1))
console.log (m.get(最长))
Console.log (m.t get('arg3')) //不存在,返回undefined
实际上,没有必要使用第三方库。我们可以用纯JavaScript。
考虑以下URL:
https://example.com?yourParamName=yourParamValue
现在我们得到:
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')
注意:
对于有多个值的参数,使用“getAll”而不是“get”
https://example.com?yourParamName[]=yourParamValue1&yourParamName[]=yourParamValue2
const yourParamName = new URLSearchParams(window.location.search).getAll('yourParamName[]')
结果如下:
["yourParamValue1", "yourParamValue2"]