React Router 不适用于 Github 页面

React Router not working with Github Pages

如果您访问我的网站,https://amodhakal.github.io/portfolio/, then you would realize that that the site is only showing the navbar, not the home page. It only shows the home page when the home tab is clicked, then if you click my navbar brand, it says 404. This website worked on a create-react-app with npm start, but it doesn't work here, nor on the build. I don't know what is wrong with the app, maybe the router setup is messed up, I don't know. I have linked the App and Index pages where I have the router setup. If you need any more information, here's the github link: https://github.com/amodhakal/portfolio,或者只是向我询问更多信息。

谢谢

索引

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom'
import App from './App';
import './styles/index.css';

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

应用程序

import { Routes, Route } from "react-router-dom";
import Navbar from "./components/Navbar";
import About from "./routes/About";
import Contact from "./routes/Contact";
import Home from "./routes/Home";
import Project from "./routes/Project";

const App = () => {
  return (
    <>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />}></Route>
        <Route path="/about" element={<About />}></Route>
        <Route path="/project" element={<Project />}></Route>
        <Route path="/contact" element={<Contact />}></Route>
      </Routes>
    </>
  );
};

export default App;
  1. 如果部署到 GitHub,请确保在 Github 中有一个 "homepage" 条目用于托管它。

    示例:

     "homepage": "https://github.com/amodhakal/portfolio",
    
  2. 切换到 HashRouter,因为 GitHub 页面不支持 BrowserRouter 使用的技术。

    索引

     import React from 'react';
     import ReactDOM from 'react-dom/client';
     import { HashRouter } from 'react-router-dom'
     import App from './App';
     import './styles/index.css';
    
     ReactDOM.createRoot(document.getElementById('root')).render(
       <React.StrictMode>
         <HashRouter>
           <App />
         </HashRouter>
       </React.StrictMode>
     );
    

有关详细信息,请参阅 deploying to GitHub Pages and notes on client-side routingcreate-react-app 文档。

想通了。这是因为 url 结构。

https://umair-mirza.github.io/safetyapp/

意味着你必须为 /safetyapp

定义一个路由

像这样:

<Route path='/safetyapp' element={<Home />} />