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