首页 文章

如何从查询字符串中获取参数值

提问于
浏览
202

如何在routes.jsx文件中定义路由,以便从服务器重定向后从Twitter的单点登录进程生成的URL中捕获 __firebase_request_key 参数值?

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>

18 回答

  • 3

    React Router v3

    React Router已经为您解析了该位置,并将其作为道具传递给您的RouteComponent . 您可以访问查询(在网址中的?之后)部分

    this.props.location.query.__firebase_request_key
    

    如果您正在寻找路径参数值,在路由器内部用冒号(:)分隔,可以通过它们访问

    this.props.match.params.redirectParam
    

    这适用于后期React Router v3版本(不确定哪个版本) . 据报道较旧的路由器版本使用 this.props.params.redirectParam .

    React Router v4

    React Router v4不再为您解析查询,但您只能通过 this.props.location.search 访问它 . 原因见nbeuchat's answer .

    例如 . 将query-string库作为 qs 导入,你可以做到

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

    此外,如果您的组件不是 Switch 的直接子项,则需要使用withRouter来访问任何路由器提供的道具 .

    General

    nizam.sp的建议

    console.log(this.props)
    

    无论如何都会有所帮助 .

  • 54

    React Router v4

    Using component

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

    使用路径道具自动渲染组件 .

    Using render

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

    路径道具传递给渲染功能 .

  • 5

    React Router v4 no longer has the props.location.query object (见github讨论) . 因此,接受的答案不适用于较新的项目 .

    v4的解决方案是使用外部库query-string来解析 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'}
    
  • 22

    React Router v4

    使用React Router v4, this.props.location.query 不再存在 . 您需要使用 this.props.location.search 来自行解析查询参数或使用现有的包(如query-string)来解析查询参数 .

    Example

    这是使用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);
    

    Rational

    React Router的团队合理删除 query 属性是:

    有许多流行的包对查询字符串解析/字符串化略有不同,并且这些差异中的每一个对于某些用户可能是“正确”的方式而对于其他用户可能是“不正确”的 . 如果React Router选择了“正确的”,它只适合某些人 . 然后,它需要为其他用户添加一种替代其首选查询解析包的方法 . React Router没有内部使用搜索字符串来要求它解析键值对,所以它不需要选择其中哪一个应该是“正确的” . [...] 4.0采用的方法是去除所有“包含电池”类型的功能,并回到基本路由 . 如果您需要查询字符串解析或异步加载或Redux集成或其他非常具体的内容,那么您可以使用专门针对您的用例的库添加它 . 您不需要的东西少,您可以根据您的特定喜好和需求定制 .

    您可以在GitHub找到完整的讨论 .

  • 50

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

    this.props.params.userId
    
  • 2

    React Router 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

  • 274

    如果您的路由器是这样的

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

    你会得到这样的id

    this.props.match.params.id
    
  • 13

    this.props.params.your_param_name 会奏效 .

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

  • 97

    如果你没有得到 this.props ...你期望基于其他答案,你可能需要使用 withRouterdocs 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))
    
  • 0

    从v4开始 React router 不再直接在其 location 对象中提供 query params . 原因是

    有许多流行的包对查询字符串解析/字符串化略有不同,并且这些差异中的每一个对于某些用户可能是“正确”的方式而对于其他用户可能是“不正确”的 . 如果React Router选择了“正确的”,它只适合某些人 . 然后,它需要为其他用户添加一种替代其首选查询解析包的方法 . React Router没有内部使用搜索字符串来要求它解析键值对,所以它不需要选择其中哪一个应该是“正确的” .

    包含它之后,只需在您的视图组件中解析期望查询对象的location.search就更有意义了 .

    您可以通过从 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)
    
  • 1

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

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

    2.你可以使用浏览器api . image当前网址是这样的:

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

    我们只想得到123;

    第一

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

    然后

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

    用一个第三个库叫做'query-string' . 首先安装它

    npm i query-string
    

    然后将其导入当前的javascript文件:

    import queryString from 'query-string'
    

    下一步是在当前网址中获取“令牌”,请执行以下操作:

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

    希望能帮助到你 .

  • 0

    我很难解决这个问题 . 如果没有上述工作,您可以尝试这样做 . 我正在使用create-react-app

    Requirements

    react-router-dom“:”^ 4.3.1“

    Solution

    在指定路由器的位置

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

    添加您想要传递的参数名称,如下所示

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

    在您渲染某些/ path的页面上,您可以指定此参数来查看参数名称调用ID,如下所示

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

    在您导出默认值的末尾

    export default withRouter(Component);
    

    请记住包含导入

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

    当console.log(this.props)你将能够传递下来的东西 . 玩得开心!

  • -3

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

    this.props.location.state.from.search

    这将显示整个查询字符串( ? 符号后的所有内容)

  • 5

    In React Router v4 only withRoute is correct way

    您可以通过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

  • 0

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

    您可以使用以下命令查看查询:

    console.log(this.props.location.query)
    
  • 5
    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
        })
    

    }

  • 5

    最简单的解决方案

    在路由:

    <Route path="/app/someUrl/:id" exact component={binder} />
    

    反应代码:

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

相关问题