如何在我的路由中定义路由。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路由器中获取查询字符串(搜索参数)

其他回答

在React Router v4中,只有withRoute才是正确的方式

您可以通过withRouter高阶组件访问历史对象的属性和最近的匹配。withRouter将在包装组件呈现时将更新的匹配、位置和历史道具传递给它。

import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (
      <div>You are now at {location.pathname}</div>
    )
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation)

https://reacttraining.com/react-router/web/api/withRouter

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

你可以创建一个简单的钩子来从当前位置提取搜索参数:

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'}

React路由器5.1+

5.1引入了各种钩子,如useLocation和useParams,可以在这里使用。

例子:

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

this.props.params。Your_param_name将工作。

这是从查询字符串中获取参数的方法。 请执行console.log(this.props);探索所有的可能性。