最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get location pathname with React Router v5 and Hooks in React v16.13.1? - Stack Overflow

programmeradmin4浏览0评论

I have some issue with React Router useLocation and how to get the current pathname.

Here is what I'm doing :

    import {BrowserRouter as Router, Switch, Route, Link} from "react-router-dom";
    import {useHistory, useLocation} from 'react-router-dom'
        
    function Home(props) {
        const [isHome, setIsHome] = useState(true);
        const [isContents, setIsContents] = useState(false);
        const [isUserProfile, setIsUserProfile] = useState(false);
        let location = useLocation();
        let history = useHistory();
    
        console.log(location)
        console.log(history)
    
        function getCurrentLocation() {
    
        }
    
        function logout() {
            const logger = fetch('/users/logout');
            logger.then(logout => {
                if (logout.ok) {
                    props.logout()
                } else {
                    console.log('error', logout);
                }
            })
        }
 
    
        return (
            <Router>
                <div className={'container-fluid h-100'}>
                    <div className={'row'}>
                        <ul className={"nav nav-tabs"}>
                            <li className={"nav-item"}>
                                <Link to={'/home'}>1</Link>
                            </li>
                            <li className={"nav-item"}>
                                <Link to={'/contents'}>2</Link>
                            </li>
                            <li className={"nav-item"}>
                                <Link to={'/user'}>3</Link>
                            </li>
                        </ul>
                    </div>
                    <Switch>
                        <Route exact path={'/home'}>1</Route>
                        <Route path={'/contents'}>2</Route>
                        <Route path={'/user'}>3</Route>
                    </Switch>
                </div>
            </Router>
        )
    };
    
    export default Home

I want to get the currentLocationPathName in order to apply some custom style. When I make a console.log(location) this is what I get back:

function useLocation() {
 if (true) {
    !(typeof useContext === "function") ?  true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__["default"])(false, "You must use React >= 16.8 in order to use useLocation()") : undefined : void 0;
  }

  return useContext(context).location;
}

Here a screenshot for more informations:

error message

I want to better understand how to use these Hooks.

Thank you for your time.

Edit:

Thank you to @Dance2die for his answer and specially this remendation:

And also make sure Home is used under a tree of a router (e.g.) BrowserRouter) (child, grandchild, etc)

I did not put Home under <Router></Router> tree...

Now it's working good and I can get access to the location.pathname.

I have some issue with React Router useLocation and how to get the current pathname.

Here is what I'm doing :

    import {BrowserRouter as Router, Switch, Route, Link} from "react-router-dom";
    import {useHistory, useLocation} from 'react-router-dom'
        
    function Home(props) {
        const [isHome, setIsHome] = useState(true);
        const [isContents, setIsContents] = useState(false);
        const [isUserProfile, setIsUserProfile] = useState(false);
        let location = useLocation();
        let history = useHistory();
    
        console.log(location)
        console.log(history)
    
        function getCurrentLocation() {
    
        }
    
        function logout() {
            const logger = fetch('/users/logout');
            logger.then(logout => {
                if (logout.ok) {
                    props.logout()
                } else {
                    console.log('error', logout);
                }
            })
        }
 
    
        return (
            <Router>
                <div className={'container-fluid h-100'}>
                    <div className={'row'}>
                        <ul className={"nav nav-tabs"}>
                            <li className={"nav-item"}>
                                <Link to={'/home'}>1</Link>
                            </li>
                            <li className={"nav-item"}>
                                <Link to={'/contents'}>2</Link>
                            </li>
                            <li className={"nav-item"}>
                                <Link to={'/user'}>3</Link>
                            </li>
                        </ul>
                    </div>
                    <Switch>
                        <Route exact path={'/home'}>1</Route>
                        <Route path={'/contents'}>2</Route>
                        <Route path={'/user'}>3</Route>
                    </Switch>
                </div>
            </Router>
        )
    };
    
    export default Home

I want to get the currentLocationPathName in order to apply some custom style. When I make a console.log(location) this is what I get back:

function useLocation() {
 if (true) {
    !(typeof useContext === "function") ?  true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__["default"])(false, "You must use React >= 16.8 in order to use useLocation()") : undefined : void 0;
  }

  return useContext(context).location;
}

Here a screenshot for more informations:

error message

I want to better understand how to use these Hooks.

Thank you for your time.

Edit:

Thank you to @Dance2die for his answer and specially this remendation:

And also make sure Home is used under a tree of a router (e.g.) BrowserRouter) (child, grandchild, etc)

I did not put Home under <Router></Router> tree...

Now it's working good and I can get access to the location.pathname.

Share Improve this question edited Jun 23, 2020 at 11:24 Yohan W. Dunon asked Mar 20, 2020 at 12:46 Yohan W. DunonYohan W. Dunon 5281 gold badge11 silver badges19 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

useHistory and useLocation are functions so you need to invoke them.

Instead of

let location = useLocation;
let history = useHistory

Invoke the hook functions.

                          
发布评论

评论列表(0)

  1. 暂无评论