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

前端 未结 10 918
你的背包
你的背包 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]);
    
    };
    
    

提交回复
热议问题