我正在 React 中创建一个博客以部署在GitHub Pages 上。
问题
- 创建了我的 React 应用程序并添加了BrowserRouter以进行导航,在 localhost 上一切正常,并且该应用程序成功部署在GitHub Pages 上。
- 尽管可以在GitHub Pages上访问主页,但如果我单击任何链接,则会出现404 错误。问题是BrowserRouter不适用于 GitHub 页面。
- 经过一番研究,我在我的React应用程序中添加了HashRouter,因为BrowserRouter无法在 GitHub 页面上运行。
- 再次使用HashRouter主页已成功加载,但如果我单击应将我从家带到博客部分的链接,预期的行为应该是这样的,
localhost:3000/#/blog
但 url 更改为类似的内容localhost:3000/blog#/
,我仍在主页上。 - 问题 4 对 localhost 和 Github Pages 都适用
但是,如果我手动输入 url,
localhost:3000/#/blog
它就可以正常工作并按预期加载博客组件。GitHub Pages上的类似行为。主页.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 链接获得,应用程序部署在这里React App