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

reactjs React.js

村村蛋蛋

2020-03-10

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

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>

第395篇《React-如何从查询字符串获取参数值》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

12个回答
乐泡芙A 2020.03.10
export class ClassName extends Component{
      constructor(props){
        super(props);
        this.state = {
          id:parseInt(props.match.params.id,10)
        }
    }
     render(){
        return(
          //Code
          {this.state.id}
        );
}
番长凯 2020.03.10

When you work with react route dom then will empty object with for match but if you do the following code then it will for es6 component as well as it works directly for function component

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>

This way you can get props and match params and profile id

This worked for me after a lot of research on es6 component.

小宇宙米亚猿 2020.03.10

most simple solution!

in routing :

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

in react code :

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 });
      });
  }
Itachi米亚斯丁 2020.03.10

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

无论有无,它都可以工作react-router下面是您的情况下的代码示例:

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>
  )
}
乐Eva 2020.03.10

React Router 5.1+

As of version 5.1 you can use the useParams hook as a helper for this kind of issue. Example:

<Route path="/docs/:id" component={Doc} />
const Doc: React.FC = React.memo(() => {
    const { id } = useParams();

    return <div>Doc ID: {id}</div>;
}
猴子Near 2020.03.10

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

this.props.location.state.from.search

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

TonyPro 2020.03.10

this.props.params.your_param_name 将工作。

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

NearL 2020.03.10
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
    })
}
逆天小胖Mandy 2020.03.10

如果您的路由器是这样的

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

你会得到这样的ID

this.props.match.params.id
小宇宙GO 2020.03.10

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

this.props.params.userId
老丝逆天 2020.03.10

反应路由器v4

使用 component

<Route path="/users/:id" component={UserPage}/> 

this.props.match.params.id

组件将使用路线道具自动渲染。


使用 render

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

this.props.match.params.id

路线道具将传递到render函数。

Green留姬 2020.03.10

反应路由器v3

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

this.props.location.query.__firebase_request_key

如果要查找路径参数值(在路由器内部用冒号(:)分隔),则可以通过以下方式访问它们

this.props.match.params.redirectParam

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

React Router v4和React Router v5

React Router v4不再为您解析查询,但您只能通过进行访问this.props.location.search由于某些原因,请参阅nbeuchat的答案

例如,您可以导入qsqs

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

另一个库是query-string有关解析搜索字符串的更多建议,请参见此答案

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

一般

nizam.sp的建议

console.log(this.props)

在任何情况下都会有帮助。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android