How to pass params with history.push/Link/Redirect in react-router v4?

前端 未结 10 914
你的背包
你的背包 2020-11-22 04:27

How can we pass parameter with this.props.history.push(\'/page\') in React-Router v4?

.then(response => {
       var r = this;
        if (re         


        
相关标签:
10条回答
  • 2020-11-22 05:13

    Extending the solution (suggested by Shubham Khatri) for use with React hooks (16.8 onwards):

    package.json (always worth updating to latest packages)
    
    {
         ...
    
         "react": "^16.12.0",
         "react-router-dom": "^5.1.2",
    
         ...
    }
    
    

    Passing parameters with history push:

    import { useHistory } from "react-router-dom";
    
    const FirstPage = props => {
        let history = useHistory();
    
        const someEventHandler = event => {
           history.push({
               pathname: '/secondpage',
               search: '?query=abc',
               state: { detail: 'some_value' }
           });
        };
    
    };
    
    export default FirstPage;
    
    
    

    Accessing the passed parameter using useLocation from 'react-router-dom':

    import { useEffect } from "react";
    import { useLocation } from "react-router-dom";
    
    const SecondPage = props => {
        const location = useLocation();
    
        useEffect(() => {
           console.log(location.pathname); // result: '/secondpage'
           console.log(location.search); // result: '?query=abc'
           console.log(location.state.detail); // result: 'some_value'
        }, [location]);
    
    };
    
    
    0 讨论(0)
  • 2020-11-22 05:13

    React TypeScript with Hooks

    From a Class

      this.history.push({
          pathname: "/unauthorized",
          state: { message: "Hello" },
        });
    

    UnAuthorized Functional Component

    interface IState {
      message?: string;
    }
    
    export default function UnAuthorized() {
      const location = useLocation();
      const message = (location.state as IState).message;
    
      return (
        <div className="jumbotron">
          <h6>{message}</h6>
        </div>
      );
    }
    
    0 讨论(0)
  • 2020-11-22 05:13

    Add on info to get query parameters.

    const queryParams = new URLSearchParams(this.props.location.search);
    console.log('assuming query param is id', queryParams.get('id');
    

    For more info about URLSearchParams check this link URLSearchParams

    0 讨论(0)
  • 2020-11-22 05:14

    I created a custom useQuery hook

    import { useLocation } from "react-router-dom";
    
    const useQuery = (): URLSearchParams => {
      return new URLSearchParams(useLocation().search)
    }
    
    export default useQuery
    

    Use it as

    const query = useQuery();
    const id = query.get("id") as string
    

    Send it as so

    history.push({  
     pathname: "/template",
     search: `id=${values.id}`,
    });
                      
    
    0 讨论(0)
提交回复
热议问题