简体   繁体   中英

Uncaught Error: useLocation() may be used only in the context of a <Router> component

I'm getting this error while using useLocation in Navbar component:

Uncaught Error: useLocation() may be used only in the context of a <Router> component

import React, { useEffect, } from 'react'
import { Link, useLocation } from 'react-router-dom'

const Navbar = () => {
  let location = useLocation();

  useEffect(() => {
    console.log(location);
  }, [location]);

  return (
    <div>
      <nav className="navbar navbar-expand-lg navbar-dark bg-dark">
        <div className="container-fluid">
          <Link className="navbar-brand" to="/navbar">Navbar</Link>
          <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span className="navbar-toggler-icon"></span>
          </button>
          <div className="collapse navbar-collapse" id="navbarSupportedContent">
            <ul className="navbar-nav me-auto mb-2 mb-lg-0">
              <li className="nav-item">
                <Link className="nav-link active" aria-current="page" to="/">Home</Link>
              </li>
              <li className="nav-item">
                <Link className="nav-link" to="/about">About</Link>
              </li>
            </ul>
            <form className="d-flex" role="search">
              <input className="form-control me-2" type="search" placeholder="Search" aria-label="Search" />
              <button className="btn btn-outline-success" type="submit">Search</button>
            </form>
          </div>
        </div>
      </nav>
    </div>
  )
}

export default Navbar

The error is informing you that the Navbar component necessarily needs to be rendered within the routing context provided by one of the routers exported by react-router / react-router-dom .

Example:

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Navbar from '../path/to/Navbar';

const App = () => (
  <Router> // <-- router provides routing context to descendents
    <Navbar /> // <-- rendered within a router component
    <Routes>
      <Route path="/" element={<h1>Home</h1>} />
      ... other routes ...
    </Routes>
  </Router>
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM