1

我有一个托管在 gh-pages 上的个人网站,并且已经部署了它等等,一切似乎都运行良好。但是我注意到路由器在主页上以及单击其他页面的链接时也可以工作,但是当我刷新 url 或手动输入时,它不起作用。

我正在将 React 与到达路由器一起使用。我已经尝试使用process.env.PUBLIC_URL我所有的链接和路径。但是,这并不能解决问题。

我的路由如下:

import React, { Component } from 'react';
import { Router } from "@reach/router";
import Home from './containers/Home';
import About from './containers/About';
import './scss/main.scss'
import Nav from './components/Nav';
import Work from './containers/Work';
import Footer from './components/Footer';

class App extends Component {
    render() {
        return (
            <div>
                <Nav/>
                <main className="wrapper">
                    <Router>
                        <Home path="/"/>
                        <About path="/about"/>
                        <Work path="/work"/>
                    </Router>
                </main>
                <Footer/>
            </div>
        );
    }
}

export default App;

当我在本地遇到这个问题时,我通过这样做来解决它

devServer: {
    historyApiFallback: true,
    contentBase: path.join(__dirname, 'public'),
    port: 9000
},

但是,由于这是 gh-pages 上的产品,我不确定是否有等价物!

有没有人有任何想法?我花了几天的时间来思考这个问题,并询问了其他几个也无法解决的开发人员!

提前致谢!

4

2 回答 2

4

So as it turned out, I figured this one out with a lot of help from google. Leaving this here for anyone who needs it!

I used this package https://www.npmjs.com/package/hash-source

Then did this:

import React, { Component } from 'react';
import Home from './containers/Home';
import About from './containers/About';
import './scss/main.scss'
import Nav from './components/Nav';
import Work from './containers/Work';
import Footer from './components/Footer';
import {
    createHistory,
    LocationProvider,
    Router
  } from "@reach/router";
  import createHashSource from 'hash-source'

  let source = createHashSource();
  let history = createHistory(source)

class App extends Component {
    render() {
        return (
            <LocationProvider history={history}>
                <div>
                    <Nav/>
                    <main className="wrapper">
                        <Router>
                            <Home path="/"/>
                            <About path="/about"/>
                            <Work path="/work"/>
                        </Router>
                    </main>
                    <Footer/>
                </div>
            </LocationProvider>
        );
    }
}

export default App;

Basically it seems gh-pages can't use the normal HTML5 push history situation, so we have to use hash history. Since reach-router doesn't support this, someone kindly made an extra library for it, and voila, it works! Thanks to that person!

于 2018-11-24T18:26:01.653 回答
0

我花了一段时间才弄清楚(关于我有<Router basename={process.env.PUBLIC_URL}>)对我有用的是将这些添加到 package.json

"build": "react-scripts build && cp build/index.html build/404.html",

它修复了 gh-pages 刷新时的崩溃

于 2021-08-06T15:48:26.407 回答