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

当前回答

componentDidMount(){
    //http://localhost:3000/service/anas
    //<Route path="/service/:serviceName" component={Service} />
    const {params} =this.props.match;
    this.setState({ 
        title: params.serviceName ,
        content: data.Content
    })
}

其他回答

我使用了一个名为query-string的外部包来解析url参数,如下所示。

import React, {Component} from 'react'
import { parse } from 'query-string';

resetPass() {
    const {password} = this.state;
    this.setState({fetching: true, error: undefined});
    const query = parse(location.search);
    return fetch(settings.urls.update_password, {
        method: 'POST',
        headers: {'Content-Type': 'application/json', 'Authorization': query.token},
        mode: 'cors',
        body: JSON.stringify({password})
    })
        .then(response=>response.json())
        .then(json=>{
            if (json.error)
                throw Error(json.error.message || 'Unknown fetch error');
            this.setState({fetching: false, error: undefined, changePassword: true});
        })
        .catch(error=>this.setState({fetching: false, error: error.message}));
}

在React-Router-Dom V5中

function useQeury() {
 const [query, setQeury] = useState({});
 const search = useLocation().search.slice(1);

 useEffect(() => {
   setQeury(() => {
     const query = new URLSearchParams(search);
     const result = {};
     for (let [key, value] of query.entries()) {
       result[key] = value;
     }
     setQeury(result);
   }, [search]);
 }, [search, setQeury]);

 return { ...query };
}


// you can destruct query search like:
const {page , search} = useQuery()

// result
// {page : 1 , Search: "ABC"}

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

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

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

也许有人可以帮助解释为什么,但如果你试图从App.js页面上的新安装的Create React App中点击props来查找位置,你会得到:

无法读取未定义的属性“搜索”

即使我有App.js作为主路径:

<Route exact path='/' render={props => (

只在App.js上,使用window。地点对我来说很合适:

import queryString from 'query-string';
...
const queryStringParams = queryString.parse(window.location.search);