Error: Invalid hook call. Hooks can only be called inside of the body of a function component. by Routing in react

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. by Routing in react

我是 React 的初学者,正在尝试做一些路由。

我正在尝试在 React 中实现路由以重定向到另一个页面,但每次我插入时,它都会显示错误:无效挂钩调用。

这是来自 App.js

的代码
    import React from 'react';
    import './App.css';
    import Nav from './Nav';
    import EKGSim from './EKGSim';
    import { BrowserRouter as Router, Routes, Route} from 'react-router-dom';
    
    function App() {
      return(
        <Router>
        <div className='App'>
          <Nav />
          <Routes>
            <Route path="/ekgsim" element={<EKGSim/>} />
          </Routes>
        </div>
        </Router>
      )
    }
    
    export default App;

谁能告诉我问题出在哪里? 我已经尝试了几个小时来寻找解决方案,但一无所获。 任何帮助将不胜感激!谢谢

Nav.js

代码
    import React from 'react';
import './App.css';

function Nav(){
    return(
        <nav>
            <h3>Home</h3>
            <ul className='nav-links'>
                <li>Was Ist EKG?</li>
                <li>EKG Component</li>
                <li>EKG Simulator</li>
            </ul>
        </nav>
    );
}

export default Nav;

和EKGSim.js

import React from 'react';
import './App.css';

function EKGSim(){
    return(
        <div>
            <h1>EKG Simulator

            </h1>
        </div>
    );
}

export default EKGSim;

你需要在 Routes 中使用 Route 试试这个

function App() {
  return (
    <Router>
      <div className="App">
        <Routes>
          <Route path="/ekgsim" element={<EKGSim/>} />
        </Routes>
      </div>
    </Router>
  );
}

问题已解决!

我只是运行这个命令npm install --save react-router-dom 而且 运行 完美!

我认为问题是我的 package.json.

中没有 react-router-dom

感谢大家的回答!