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

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

在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路由器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)

无论如何都会有帮助的。