【问题标题】:No get query sting data in react没有在反应中获取查询字符串数据
【发布时间】:2021-02-22 07:29:39
【问题描述】:

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

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"
  },

这是错误图片。

【问题讨论】:

  • 您没有显示将哪些道具传递到您的 App 组件中。传入了什么道具?
  • 从您用于访问查询参数的语法来看,我假设您使用的是react-router,但我看不到它作为依赖项添加到您的package.json 中。跨度>
  • 您的props 中没有location

标签: javascript node.js reactjs get query-string


【解决方案1】:

您没有使用 react router ,因此 props 中没有 location 参数:

所以你有两个解决方案,

  • 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');

【讨论】:

    【解决方案2】:

    需要通过道具喜欢

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

    并收到喜欢

    handleQueryString(arg) {
    ....
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-13
      • 2011-03-12
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多