在反应中没有获取查询字符串数据

No get query sting data in react

我正在尝试获取查询字符串参数,但是它是空白的。 这是 URL.

https://master.deeiswmgeowge.amplifyapp.com/?site=gfg&subject=react

那么,this.props为空

以下为出处

import React, { Component } from "react"; 
// Importing Module 
import queryString from 'query-string'
  
class App extends Component { 
  
  state = { 
    site: 'unknown', 
    subject: 'i dont know'
  } 
  
  handleQueryString = () => { 
    // Parsing the query string  
    // Using parse method 
    console.log(`this.props`, this.props)
    let queries = queryString.parse(this.props.location.search) 
    console.log(queries) 
    this.setState(queries) 
  } 
  
  render() { 
    return ( 
      <div style={{ margin: 200 }}> 
          
        <p> WebSite: {this.state.site} </p> 
          
                  
        <p> Subject: {this.state.subject} </p> 
  
        <button 
          onClick={this.handleQueryString} 
          className='btn btn-primary'> 
          click me 
        </button> 
      </div> 
    ); 
  } 
} 
  
export default App;
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "query-string": "^6.14.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "4.0.2",
    "web-vitals": "^1.0.1"
  },

这是错误图片。

需要传递道具

onClick={()=>  this.handleQueryString(this.props)} 

并收到赞

handleQueryString(arg) {
....
}

你没有使用 react router ,因此 props 中没有位置参数:

所以你有两个解决方案,

  • 1 是否添加 react-router-dom 并使用路由器包装您的应用程序,(或使用路由器钩子,如 export default withRouter(App)

  • 2 或直接访问 window.location.search 并使用 URLSearchParams

    获取参数

举例:

const urlParams = new URLSearchParams(window.location.search);
const site = urlParams.get('site');
const subject = urlParams.get('subject');