React 应用程序 HashRouter 无法在本地主机和 Github 用户页面上运行

2024-04-08

我正在 React 创建一个博客以部署在GitHub 页面.

Problem

  1. 创建了我的 React 应用程序并添加了浏览器路由器对于导航,本地主机上一切正常,并且应用程序成功部署在GitHub 页面.
  2. 尽管可以在以下位置访问主页GitHub 页面,如果我点击任何链接,就会出现404错误。问题是浏览器路由器不适用于 GitHub 页面。
  3. 经过一番研究后我添加了哈希路由器在我的反应应用程序中浏览器路由器无法在 GitHub 页面上工作。
  4. With 哈希路由器主页再次成功加载,但如果我单击链接,应该将我从博客之家部分预期的行为应该是这样的localhost:3000/#/blog但网址更改为类似的内容localhost:3000/blog#/而且我还在主页上。
  5. 问题 4 对于 localhost 和 Github Pages 都适用
  6. 但如果我手动输入网址localhost:3000/#/blog它工作得很好并加载Blog组件符合预期。类似行为在GitHub 页面.

    Home.js

import React from 'react';
import { Component } from 'react';
import HODL from './HODL';
import Header from './Header';
import { HashRouter as Router, Switch, Route } from 'react-router-dom';
import Jargons from './Jargons';

class Home extends Component {

  render () {

    return (
      <Router basename={process.env.PUBLIC_URL + "/"}>
        <Header />
        <Switch>
          <Route path="/" exact component={HODL} />
          <Route path="/blog" component={Blog} />
          <Route path="/tutorials/javascript" component={JavaScript} />
          <Route path="/tutorials/solidity" component={Solidity} />
          <Route path="/jargons" component={Jargons} />
        </Switch>
      </Router>
    );
  }
}

export default Home;

无论有或没有,工作原理都相同basename={process.env.PUBLIC_URL + "/"}

包.json

{
  "name": "block-by-block.github.io",
  "version": "0.1.0",
  "private": true,
  "homepage": "https://block-by-block.github.io",
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1",
    "bootstrap": "^4.4.1",
    "gh-pages": "^2.1.1",
    "jquery": "^3.4.1",
    "popper.js": "^1.16.1",
    "react-bootstrap": "^1.0.0",
    "react-markdown": "^4.3.1",
    "react-router-dom": "^5.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "predeploy": "npm run build",
    "deploy": "gh-pages -b master -d build"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

PS :完整的源代码位于Github链接 https://github.com/block-by-block/website该应用程序部署在这里反应应用程序 https://block-by-block.github.io/


所以我发现问题出在你的 Header 组件上。 您正在使用与react-router-dom不兼容的bootstrap。欲了解更多信息,请在谷歌上查找。

这是您应该更改的内容:

import { Link } from "react-router-dom";

<Nav.Link as={Link} to="/jargons">
   Jargons that works!
</Nav.Link>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React 应用程序 HashRouter 无法在本地主机和 Github 用户页面上运行 的相关文章

随机推荐