Getting query parameters from react-router hash fragment

后端 未结 9 1561
心在旅途
心在旅途 2020-12-04 11:55

I\'m using react and react-router for my application on the client side. I can\'t seem to figure out how to get the following query parameters from a url like:



        
9条回答
  •  一整个雨季
    2020-12-04 12:20

    With stringquery Package:

    import qs from "stringquery";
    
    const obj = qs("?status=APPROVED&page=1limit=20");  
    // > { limit: "10", page:"1", status:"APPROVED" }
    

    With query-string Package:

    import qs from "query-string";
    const obj = qs.parse(this.props.location.search);
    console.log(obj.param); // { limit: "10", page:"1", status:"APPROVED" } 
    

    No Package:

    const convertToObject = (url) => {
      const arr = url.slice(1).split(/&|=/); // remove the "?", "&" and "="
      let params = {};
    
      for(let i = 0; i < arr.length; i += 2){
        const key = arr[i], value = arr[i + 1];
        params[key] = value ; // build the object = { limit: "10", page:"1", status:"APPROVED" }
      }
      return params;
    };
    
    
    const uri = this.props.location.search; // "?status=APPROVED&page=1&limit=20"
    
    const obj = convertToObject(uri);
    
    console.log(obj); // { limit: "10", page:"1", status:"APPROVED" }
    
    
    // obj.status
    // obj.page
    // obj.limit
    

    Hope that helps :)

    Happy coding!

提交回复
热议问题