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

当前回答

试试这个

http://localhost:4000/#/amoos?id=101

// ReactJS
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); //101
}



// VanillaJS
const id = window.location.search.split("=")[1];
console.log(id); //101

其他回答

实际上,没有必要使用第三方库。我们可以用纯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"]

从v4开始,React路由器不再直接在其location对象中提供查询参数。原因是

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".

包含了这个之后,只解析location会更有意义。在需要查询对象的视图组件中搜索。

你可以通过覆盖react-router中的withRouter来实现这一点

customWithRouter.js

import { compose, withPropsOnChange } from 'recompose';
import { withRouter } from 'react-router';
import queryString from 'query-string';

const propsWithQuery = withPropsOnChange(
    ['location', 'match'],
    ({ location, match }) => {
        return {
            location: {
                ...location,
                query: queryString.parse(location.search)
            },
            match
        };
    }
);

export default compose(withRouter, propsWithQuery)

最受欢迎的答案中的链接是死的,因为SO不让我评论,对于ReactRouter v6.3.0,你可以使用params钩子

import * as React from 'react';
import { Routes, Route, useParams } from 'react-router-dom';

function ProfilePage() {
  // Get the userId param from the URL.
  let { userId } = useParams();
  // ...
}

function App() {
  return (
    <Routes>
      <Route path="users">
        <Route path=":userId" element={<ProfilePage />} />
        <Route path="me" element={...} />
      </Route>
    </Routes>
  );
}

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路由器中获取查询字符串(搜索参数)

React路由器Dom V6 https://reactrouter.com/docs/en/v6/hooks/use-search-params

import * as React from "react";
import { useSearchParams } from "react-router-dom";

function App() {
  let [searchParams, setSearchParams] = useSearchParams();

  function handleSubmit(event) {
    event.preventDefault();
    // The serialize function here would be responsible for
    // creating an object of { key: value } pairs from the
    // fields in the form that make up the query.
    let params = serializeFormQuery(event.target);
    setSearchParams(params);
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>{/* ... */}</form>
    </div>
  );
}

直到React路由器Dom V5

function useQueryParams() {
    const params = new URLSearchParams(
      window ? window.location.search : {}
    );

    return new Proxy(params, {
        get(target, prop) {
            return target.get(prop)
        },
    });
}

React钩子很棒

如果你的url看起来像/users?页面= 2数= 10字段=姓名、电子邮件、电话

// app.domain.com/users?page=2&count=10&fields=name,email,phone

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

console.log({ page, fields, count })
console.log({ unknown })

如果您的查询参数包含hyphone("-")或空格(" ") 然后你不能像{page, fields, count,…未知的}

你需要做传统的作业,比如

// app.domain.com/users?utm-source=stackOverFlow

const params = useQueryParams();

console.log(params['utm-source']);