简体   繁体   中英

Error While adding React Router DOM: Invalid hook call. Hooks can only be called inside of the body of a function component

I am new to React. I was just creating a notes app in react. Everything was fine. But when I use React Router, I get the error of "Error: Invalid hook call. Hooks can only be called inside of the body of a function component ". And it is only showing when I add a Router, if I remove it then the error has gone. I have also attached the screenshot. 错误截图

My app.js

import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import "./App.css";
import Header from "./components/Header";
import NoteslistPages from "./pages/NoteslistPages";
import Footer from "./components/Footer";


 return (
    <Router>
      <div className="App">
        <Header />
        <Route path="/" exact component={NoteslistPages} />
        

        <Footer />
      </div>
    </Router>
  );
}

export default App;




Your code does not represent a functional component, and as written in the error message, a hook must be called within a body of such. Maybe you removed some code by mistake, because you also have one "}" bracket which closes nothing.

Add function declaration and it should work fine:

import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import "./App.css";
import Header from "./components/Header";
import NoteslistPages from "./pages/NoteslistPages";
import Footer from "./components/Footer";

function App() {

 return (
  <Router>
   <div className="App">
    <Header />
    <Route path="/" exact component={NoteslistPages} />
    <Footer />
   </div>
  </Router>
 );
}

export default App;

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