javascript 路由不工作,给我一个错误“你不能渲染一个< Router>在另一个< Router>,你不应该有一个以上的应用程序”

2vuwiymt  于 2023-06-20  发布在  Java
关注(0)|答案(1)|浏览(224)

我使用的是“react-router-dom”:“^6.11.2”
未捕获错误:不能在另一个<Router>中渲染<Router>。你永远不应该在你的应用程序中有一个以上。

- at invariant (history.ts:480:
- at Router (components.tsx:335:1)
- at renderWithHooks (react-dom.development.js:16305:1)
- at mountIndeterminateComponent (react-dom.development.js:20074:1)
- at beginWork (react-dom.development.js:21587:1)
- at beginWork$1 (react-dom.development.js:27426:1)
- at performUnitOfWork (react-dom.development.js:26557:1)
- at workLoopSync (react-dom.development.js:26466:1)
- at renderRootSync (react-dom.development.js:26434:1)
- at recoverFromConcurrentError (react-dom.development.js:25850:1)]]

App.js

import { Routes, Route} from 'react-router-dom';

function App() {
  return (
    <>
      <Navbar title="TextUtils" aboutText="About TextUtils" mode={Mode} toggleMode={toggleMode} btnText={btnText} />
      <ALERTS Alert={alert} />

      <div className='container my-3'>
        <Routes>
          <Route path="/" element={<TextForm heading="Enter text to analyze" mode={Mode} />} />
          <Route path="about" element={<About />} />
        </Routes>
      </div>
    </>
  );
}
export default App;

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 as Router} from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Router>
      <App />
    </Router>
  </React.StrictMode>
);

reportWebVitals();
w46czmvw

w46czmvw1#

我相信react-router-dom@6,当你想定义和使用BrowserRouter时,你需要在代码中创建它,如下所示。

import {
  createBrowserRouter,
  RouterProvider,
} from "react-router-dom";

const router = createBrowserRouter([
  {
    path: "/",
    element: <Root />,
    loader: rootLoader,
    children: [
      {
        path: "team",
        element: <Team />,
        loader: teamLoader,
      },
    ],
  },
]);

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
   <RouterProvider router={router} />
      <App />
    </RouterProvider>
  </React.StrictMode>
);

下面是参考:https://reactrouter.com/en/main/routers/create-browser-router#createbrowserrouter

相关问题