如何在我的路由中定义路由。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>
React路由器v6
来源:在React路由器中获取查询字符串(搜索参数)
使用新的useSearchParams钩子和.get()方法:
const Users = () => {
const [searchParams] = useSearchParams();
console.log(searchParams.get('sort')); // 'name'
return <div>Users</div>;
};
使用这种方法,您可以读取一个或几个参数。
将参数作为一个对象:
如果你需要一次性获得所有的查询字符串参数,那么我们可以像这样使用Object.fromEntries:
const Users = () => {
const [searchParams] = useSearchParams();
console.log(Object.fromEntries([...searchParams])); // ▶ { sort: 'name', order: 'asecnding' }
return <div>Users</div>;
};
阅读更多和现场演示:在React路由器中获取查询字符串(搜索参数)
实际上,没有必要使用第三方库。我们可以用纯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"]