BrowserRouter 导致 React App 无法加载 (react-router-dom)

BrowserRouter causes React App to not load (react-router-dom)

如果我删除下面的 <Router></Router> 标签,应用程序将照常加载。但是添加这些结果会出现空白页面(应用程序不会加载)

奇怪的是,如果我把这些标签转成评论,也会出现这个问题。例如。 //<Router>//</Router>.

我安装了最新的 (v6) react-router-dom。如果我改用 HashRouter 也会出现这个问题。

来自我的index.js:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import {
  BrowserRouter as Router,
  Routes,
  Route
} from "react-router-dom";
import reportWebVitals from './reportWebVitals';

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

reportWebVitals();

来自我的App.js

import React from 'react';
import {
  BrowserRouter as Router,
  Routes,
  Route
} from "react-router-dom";

function App(){
  return(
    <h1>Hi</h1>
  );
}

export default App;

Package.json

{
  "name": "test-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.2.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

似乎 react-router-dom 尚未作为依赖项添加到您的项目中,并且可能未在您构建应用程序时在本地安装。

"dependencies": {
  "@testing-library/jest-dom": "^5.16.4",
  "@testing-library/react": "^13.2.0",
  "@testing-library/user-event": "^13.5.0",
  "react": "^18.1.0",
  "react-dom": "^18.1.0",
  "react-scripts": "5.0.1",
  "web-vitals": "^2.1.4"
},

运行 npm install –save react-router-domnpm i -S react-router-dom)安装并添加react-router-dom到项目的依赖项。

从这里您应该可以将路由器代码添加到您的应用程序中,然后 运行 使用 npm start