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

this.props.params。Your_param_name将工作。

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


React路由器v6,使用钩子

在react-router-dom v6中,有一个名为useSearchParams的新钩子。所以,

const [searchParams, setSearchParams] = useSearchParams();
searchParams.get("__firebase_request_key")

你会得到“blablabla”。注意,searchParams是URLSearchParams的一个实例,它也实现了一个迭代器,例如用于使用Object.fromEntries等。

React Router v4/v5,没有钩子,通用

React Router v4不再为你解析查询,但你只能通过this.props.location.search(或useLocation,见下文)访问它。原因见nbeuchat的答案。

例如,你可以用qs库导入qs

qs.parse(this.props.location.search, { ignoreQueryPrefix: true }).__firebase_request_key

另一个库是query-string。有关解析搜索字符串的更多想法,请参阅这个答案。如果你不需要ie兼容性,你也可以使用

new URLSearchParams(this.props.location.search).get("__firebase_request_key")

对于功能组件,你可以用钩子useLocation替换this.props.location。注意,你可以使用window.location。搜索,但这将不允许在更改时触发React渲染。 如果你的(非功能性的)组件不是Switch的直接子组件,你需要使用throuter来访问路由器提供的任何道具。

React路由器v3

React Router已经为你解析了位置,并将它作为道具传递给你的RouteComponent。您可以访问查询(在?在url)部分通过

this.props.location.query.__firebase_request_key

如果你在路由器中寻找用冒号(:)分隔的路径参数值,这些可以通过

this.props.match.params.redirectParam

这适用于最新的React Router v3版本(不确定是哪个)。旧版本的路由器报告使用this.props.params.redirectParam。

一般

尼扎姆。Sp的建议

console.log(this.props)

无论如何都会有帮助的。


你可以检查react-router,简单地说,你可以使用代码获取查询参数,只要你在路由器中定义:

this.props.params.userId

在需要访问可以使用的参数的组件中

this.props.location.state.from.search

这将显示整个查询字符串(在?标志)


React路由器v4

使用组件

<Route path="/users/:id" component={UserPage}/> 
this.props.match.params.id

该组件自动使用路由道具呈现。


使用渲染

<Route path="/users/:id" render={(props) => <UserPage {...props} />}/> 
this.props.match.params.id

路由道具被传递给渲染函数。


如果你没有得到这个。道具…根据其他答案,您可能需要使用withthrouter (docs v4):

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 TwitterSsoButton = withRouter(ShowTheLocation)  

// This gets around shouldComponentUpdate
withRouter(connect(...)(MyComponent))

// This does not
connect(...)(withRouter(MyComponent))

React Router v4不再有props.location.query对象(见github讨论)。因此,已接受的答案将不适用于较新的项目。

v4的解决方案是使用外部库查询字符串来解析props.location.search

const qs = require('query-string');
//or
import * as qs from 'query-string';

console.log(location.search);
//=> '?foo=bar'

const parsed = qs.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}

如果你的路由器是这样的

<Route exact path="/category/:id" component={ProductList}/>

你会得到这样的id

this.props.match.params.id

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上找到完整的讨论。


React路由器v4

const urlParams = new URLSearchParams(this.props.location.search)
const key = urlParams.get('__firebase_request_key')

请注意,它目前还处于试验阶段。

查看浏览器兼容性:https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams#Browser_compatibility


在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


我使用了一个名为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}));
}

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


最简单的解决方案!

在路由方面:

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

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

我花了很长时间才解决这个问题。如果以上都不行,你可以试试这个。我正在使用创建-反应应用程序

需求

react-router-dom ^ 4.3.1“:

解决方案

在指定路由器的位置

<Route path="some/path" ..../>

像这样添加您想要传入的参数名

<Route path="some/path/:id" .../>

在你渲染一些/路径的页面上,你可以指定这个来查看参数名调用id,就像这样

componentDidMount(){
  console.log(this.props);
  console.log(this.props.match.params.id);
}

在导出默认值的最后

export default withRouter(Component);

记住要包含import

import { withRouter } from 'react-router-dom'

当console.log(this.props)时,你就可以知道传递了什么。玩得开心!


据我所知,有三种方法可以做到。

1.使用正则表达式获取查询字符串。

2.您可以使用浏览器api。 图片当前的url是这样的:

http://www.google.com.au?token=123

我们只想得到123;

第一个

 const query = new URLSearchParams(this.props.location.search);

Then

const token = query.get('token')
console.log(token)//123

使用第三个名为“query-string”的库。 首先安装它 NPM I查询字符串 然后导入到当前的javascript文件中: 导入query-string

下一步是在当前url中获取'token',请执行以下操作:

const value=queryString.parse(this.props.location.search);
const token=value.token;
console.log('token',token)//123

2019年2月25日更新

4. 如果当前url如下所示:

http://www.google.com.au?app=home&act=article&aid=160990

我们定义一个函数来获取参数:

function getQueryVariable(variable)
{
        var query = window.location.search.substring(1);
        console.log(query)//"app=article&act=news_content&aid=160990"
        var vars = query.split("&");
        console.log(vars) //[ 'app=article', 'act=news_content', 'aid=160990' ]
        for (var i=0;i<vars.length;i++) {
                    var pair = vars[i].split("=");
                    console.log(pair)//[ 'app', 'article' ][ 'act', 'news_content' ][ 'aid', '160990' ] 
        if(pair[0] == variable){return pair[1];}
         }
         return(false);
}

我们可以通过以下方式获得“援助”:

getQueryVariable('aid') //160990

let data = new FormData();
data.append('file', values.file);

export class ClassName extends Component{
      constructor(props){
        super(props);
        this.state = {
          id:parseInt(props.match.params.id,10)
        }
    }
     render(){
        return(
          //Code
          {this.state.id}
        );
}

也许有点晚了,但是这个react钩子可以帮助你在URL查询中获取/设置值:https://github.com/rudyhuynh/use-url-search-params(由我编写)。

不管有没有反应路由器,它都可以工作。 下面是您案例中的代码示例:

import React from "react";
import { useUrlSearchParams } from "use-url-search-params";

const MyComponent = () => {
  const [params, setParams] = useUrlSearchParams()
  return (
    <div>
      __firebase_request_key: {params.__firebase_request_key}
    </div>
  )
}

当使用React钩子时,没有访问this.props.location的权限。 要获取url参数,请使用窗口对象。

const search = window.location.search;
const params = new URLSearchParams(search);
const foo = params.get('bar');

或者像这样?

Let win = { “位置”:{ “路径”:“http://localhost: 8000 / # / signin吗?_k = v9ifuf&__firebase_request_key =之类的 } } If (win.location.path.match('__firebase_request_key').length) { 让key= win.location.path.split('__firebase_request_key=')[1] console.log(关键) }


当你使用react route dom时,将用for match清空对象,但如果你执行以下代码,则它将用于es6组件,以及它直接用于函数组件

import { Switch, Route, Link } from "react-router-dom";

<Route path="/profile" exact component={SelectProfile} />
<Route
  path="/profile/:profileId"
  render={props => {
    return <Profile {...props} loading={this.state.loading} />;
  }}
/>
</Switch>
</div>

通过这种方式,您可以获得道具并匹配参数和配置文件id

在对es6组件进行了大量研究后,这对我来说很有效。


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

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

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

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

假设有一个url如下所示

http://localhost:3000/callback?code=6c3c9b39-de2f-3bf4-a542-3e77a64d3341

如果我们想从该URL提取代码,下面的方法将工作。

const authResult = new URLSearchParams(window.location.search); 
const code = authResult.get('code')

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

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路由器v5.1引入了钩子:

For

<Route path="/posts/:id">
  <BlogPost />
</Route>

你可以通过hook访问params / id:

const { id } = useParams();

更多的在这里。


也许有人可以帮助解释为什么,但如果你试图从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);

在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-location-query包,例如:

  const [name, setName] = useLocationField("name", {
    type: "string",
    initial: "Rostyslav"
  });

  return (
    <div className="App">
      <h1>Hello {name}</h1>
      <div>
        <label>Change name: </label>
        <input value={name} onChange={e => setName(e.target.value)} />
      </div>
    </div>
  );

名称-获取价值 setName =设置值

这个包有很多选项,在Github上的文档中阅读更多


在没有第三方库或复杂的解决方案的情况下,在一行中完成这一切。以下是如何

let myVariable = new URLSearchParams(history.location.search).get('business');

你唯一需要改变的是你自己的参数名称的单词“business”。

业务= url.com例子吗?你好

myVariable的结果将是hello


不是反应的方式,但我相信这个单行函数可以帮助你:)

const getQueryParams = (query = null) => [...(new URLSearchParams(query||window.location.search||"")).entries()].reduce((a,[k,v])=>(a[k]=v,a),{});

或:

const getQueryParams = (query = null) => (query||window.location.search.replace('?','')).split('&').map(e=>e.split('=').map(decodeURIComponent)).reduce((r,[k,v])=>(r[k]=v,r),{});

或完整版:

const getQueryParams = (query = null) => {
  return (
    (query || window.location.search.replace("?", ""))

      // get array of KeyValue pairs
      .split("&") 

      // Decode values
      .map((pair) => {
        let [key, val] = pair.split("=");

        return [key, decodeURIComponent(val || "")];
      })

      // array to object
      .reduce((result, [key, val]) => {
        result[key] = val;
        return result;
      }, {})
  );
};

例子: URL:…?= = 1 b =建发集团有限公司的测试 代码:

getQueryParams()
//=> {a: "1", b: "c", d: "test"}

getQueryParams('type=user&name=Jack&age=22')
//=> {type: "user", name: "Jack", age: "22" }

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

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

你可以使用下面的react钩子:

如果url改变,钩子状态会更新 SSR: typeof window === "undefined",只是检查窗口导致错误(尝试一下) 代理对象隐藏实现,因此返回undefined而不是null

这是获取搜索参数为对象的函数:

const getSearchParams = <T extends object>(): Partial<T> => {
    // server side rendering
    if (typeof window === "undefined") {
        return {}
    }

    const params = new URLSearchParams(window.location.search) 

    return new Proxy(params, {
        get(target, prop, receiver) {
            return target.get(prop as string) || undefined
        },
    }) as T
}

然后像这样把它用作钩子:

const useSearchParams = <T extends object = any>(): Partial<T> => {
    const [searchParams, setSearchParams] = useState(getSearchParams())

    useEffect(() => {
        setSearchParams(getSearchParams())
    }, [typeof window === "undefined" ? "once" : window.location.search])

    return searchParams
}

如果你的url是这样的:

/app?page=2&count=10

你可以这样读:

const { page, count } = useQueryParams();

console.log(page, count)

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
}

使用let {redirectParam} = useParams();如果你用的是功能组件

它是一个类组件

constructor (props) {  
        super(props);
        console.log(props);
        console.log(props.match.params.redirectParam)
}
async componentDidMount(){ 
        console.log(this.props.match.params.redirectParam)
}

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


试试这个

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

你可以使用这个用Typescript写的简单钩子:

const useQueryParams = (query: string = null) => {      
    const result: Record<string, string> = {};
    new URLSearchParams(query||window.location.search).forEach((value, key) => {
      result[key] = value;
    });
    return result;
}

用法:

// http://localhost:3000/?userId=1889&num=112
const { userId, num } = useQueryParams();
// OR
const params = useQueryParams('userId=1889&num=112');

在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"}


您可以使用这段代码来获取作为对象的参数。如果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);


最受欢迎的答案中的链接是死的,因为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>
  );
}

容易解构分配URLSearchParams

测试尝试如下:

1 扫描:https://www.google.com/?param1=apple&param2=banana

2 右键单击>页,单击Inspect > goto Console选项卡 然后粘贴下面的代码:

const { param1, param2 } = Object.fromEntries(new URLSearchParams(location.search));
console.log("YES!!!", param1, param2 );

输出:

YES!!! apple banana

你可以扩展params,如param1, param2,想扩展多少就扩展多少。