如何在我的路由中定义路由。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>

当前回答

您可以使用这段代码来获取作为对象的参数。如果url中没有查询参数,该对象将为空

let url = window.location.toString(); Let params = url?.split("?")[1]?.split("&"); 让obj = {}; params?.forEach((el) => { Let [k, v] = el?.split("="); obj[k] = v.replaceAll("%20", " " "); }); console.log (obj);

其他回答


最简单的解决方案!

在路由方面:

   <Route path="/app/someUrl/:id" exact component={binder} />

在react代码中:

componentDidMount() {
    var id = window.location.href.split('/')[window.location.href.split('/').length - 1];
    var queryString = "http://url/api/controller/" + id
    $.getJSON(queryString)
      .then(res => {
        this.setState({ data: res });
      });
  }

React路由器v3

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

React路由器v4

在React Router v4中,this.props.location.query不再存在。您需要使用this.props.location.search,并自己或使用现有的包(如query-string)解析查询参数。

例子

下面是一个使用React Router v4和query-string库的最小示例。

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

理性的

React Router团队移除query属性的理由是:

There are a number of popular packages that do query string parsing/stringifying slightly differently, and each of these differences might be the "correct" way for some users and "incorrect" for others. If React Router picked the "right" one, it would only be right for some people. Then, it would need to add a way for other users to substitute in their preferred query parsing package. There is no internal use of the search string by React Router that requires it to parse the key-value pairs, so it doesn't have a need to pick which one of these should be "right". [...] The approach being taken for 4.0 is to strip out all the "batteries included" kind of features and get back to just basic routing. If you need query string parsing or async loading or Redux integration or something else very specific, then you can add that in with a library specifically for your use case. Less cruft is packed in that you don't need and you can customize things to your specific preferences and needs.

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

在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

有了这一行代码,你可以在React Hook和React Class Component的任何地方使用它。

https://www.hunterisgod.com/?city=Leipzig

let city = (new URLSearchParams(window.location.search)).get("city")

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
}