简体   繁体   中英

Can't resolve Invalid Hook Call error (in conjunction with React Router)

I'm having an issue with rendering components. I get an 'Invalid Hook call' error in my console. I've tried to check for the three main 'causes' as per the React docs , but I can't seem to find what it is. I'm using React Router and trying to set up the skeleton for my website. Full repository . (Before installing (and setting up) React Router, everything worked just fine...)

No duplicate React as far as I can tell: 运行 npm ls react 后

Here's my Header.js :

import React, { useState } from "react";
import { Routes, Route, Link } from "react-router-dom";
import { Over } from "../../pages/Over";
import { Partners } from "../../pages/Partners";
import { Contact } from "../../pages/Contact";
import { NavBar } from "./Header.styled";

export const Header = () => {
  const [isOpen, setIsOpen] = useState(false);

  const handleToggle = () => {
    setIsOpen((prevIsOpen) => !prevIsOpen);
  };

  return (
    <>
      <NavBar>
        <nav className="navBar">
          <button onClick={handleToggle}>{isOpen ? "Close" : "Open"}</button>
          <ul className={`menuNav ${isOpen ? " showMenu" : ""}`}>
            <li>
              <Link to="/over">Over</Link>
            </li>
            <li>
              <Link to="/partners">Partners</Link>
            </li>
            <li>
              <Link to="/contact">Contact</Link>
            </li>
          </ul>

          <Routes>
            <Route path="over" element={<Over />} />
            <Route path="partners" element={<Partners />} />
            <Route path="contact" element={<Contact />} />
          </Routes>
        </nav>
      </NavBar>
    </>
  );
};

Here's my index.js

import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import "./index.css";
import { App } from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
  <BrowserRouter>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </BrowserRouter>
);

I just checked your repository and couldn't find react-router-dom in your package.json file. Maybe you installed it in a different directory, so reinstalling it in the root level (where your package.json) is located is should solve the issue.

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