我的index.js文件中有一个路由器组件,它似乎不能正常工作。
以下是我尝试过的:
index.js
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
// import reportWebVitals from "./reportWebVitals";
import { BrowserRouter } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
        <BrowserRouter>
          <App />
        </BrowserRouter>
);app.jsx
import logo from './logo.svg';
import './App.css';
function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}
export default App;屏幕为空白,控制台给出了此错误。
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.我正在学习本教程:https://blog.logrocket.com/react-router-v6/。使用react-router版本6
发布于 2022-11-01 08:26:55
对于react路由器v6.4使用createBrowserRouter创建您的路由器
import React from "react";
import { createRoot } from "react-dom/client";
import {
  createBrowserRouter,
  RouterProvider,
  Route,
  Link,
} from "react-router-dom";
const router = createBrowserRouter([
  {
    path: "/",
    element: (
      <div>
        <h1>Hello World</h1>
        <Link to="about">About Us</Link>
      </div>
    ),
  },
  {
    path: "about",
    element: <div>About</div>,
  },
]);
createRoot(document.getElementById("root")).render(
  <RouterProvider router={router} />
);发布于 2022-11-01 07:36:17
在V6中,您可以尝试以下方法
import React from 'react'
import { BrowserRouter, Routes, Route} from "react-router-dom"
import "./index.css"
import App from "./App"
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<>
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<App />} />
      </Routes>
    </BrowserRouter>
</>
)https://stackoverflow.com/questions/74272764
复制相似问题