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

当前回答

在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上的文档中阅读更多

如果你的路由器是这样的

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

你会得到这样的id

this.props.match.params.id

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

试试这个

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