How to parse query string in react-router v4

前端 未结 7 979
孤独总比滥情好
孤独总比滥情好 2020-12-04 16:27

In react-router v3 I could access it with props.location.query.foo (if the current location was ?foo=bar)

In react-router-dom@4.0.0

7条回答
  •  北海茫月
    2020-12-04 17:11

    instead of installing a package you can use a simple function for extracting your query params.

    //Param Extractor
    const parseParams = (params = "") => {
      const rawParams = params.replace("?", "").split("&");
      const extractedParams = {};
      rawParams.forEach((item) => {
        item = item.split("=");
        extractedParams[item[0]] = item[1];
      });
      return extractedParams;
    };
    
    //Usage
    const params = parseParams(this.props?.location?.search); // returns an object like:
    // {id:1,name:john...}
    
    

提交回复
热议问题