How do you programmatically update query params in react-router?

后端 未结 8 2050
Happy的楠姐
Happy的楠姐 2020-11-29 21:41

I can\'t seem to find how to update query params with react-router without using . hashHistory.push(url) doesn\'t seem to register que

8条回答
  •  青春惊慌失措
    2020-11-29 22:22

        for react-router v4.3, 
    
     const addQuery = (key, value) => {
      let pathname = props.location.pathname; 
     // returns path: '/app/books'
      let searchParams = new URLSearchParams(props.location.search); 
     // returns the existing query string: '?type=fiction&author=fahid'
      searchParams.set(key, value);
      this.props.history.push({
               pathname: pathname,
               search: searchParams.toString()
         });
     };
    
      const removeQuery = (key) => {
      let pathname = props.location.pathname; 
     // returns path: '/app/books'
      let searchParams = new URLSearchParams(props.location.search); 
     // returns the existing query string: '?type=fiction&author=fahid'
      searchParams.delete(key);
      this.props.history.push({
               pathname: pathname,
               search: searchParams.toString()
         });
     };
    
    
     ```
    
     ```
     function SomeComponent({ location }) {
       return 
    ; } ``` // To know more on URLSearchParams from [Mozilla:][1] var paramsString = "q=URLUtils.searchParams&topic=api"; var searchParams = new URLSearchParams(paramsString); //Iterate the search parameters. for (let p of searchParams) { console.log(p); } searchParams.has("topic") === true; // true searchParams.get("topic") === "api"; // true searchParams.getAll("topic"); // ["api"] searchParams.get("foo") === null; // true searchParams.append("topic", "webdev"); searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev" searchParams.set("topic", "More webdev"); searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev" searchParams.delete("topic"); searchParams.toString(); // "q=URLUtils.searchParams" [1]: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

提交回复
热议问题