当我在本地服务器上重新加载我的应用程序时,一切都很好。但是当我在 gh-pages 上托管时重新加载页面时,出现 404 错误。它不会在主页上执行此操作,但会在其他两个页面上执行此操作。这是否与远程托管有关?我对 React Router 有点菜鸟。任何帮助将不胜感激。下面是相关代码和我的应用程序的链接:
反应游戏应用程序 https://envincebal.github.io/react-game-search/
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Nav />
<div className="container">
<Switch>
<Route exact path="/react-game-search" component={MainPage} />
<Route path="/games" component={GameSearch} />
<Route path="/about" component={About} />}
<Route path="/details" component={GamesDetails} />}
</Switch>
</div>
</div>
</Router>
);
}
}
const Nav = () => {
return (
<div className="navbar">
<div className="navbar-item">
<NavLink
exact to="/react-game-search/"
activeClassName="selected"
className="nav-link"
>Home</NavLink>
</div>
<div className="navbar-item">
<NavLink
to="/games"
activeClassName="selected"
className="nav-link"
>Games</NavLink>
</div>
<div className="navbar-item">
<NavLink
to="/about"
activeClassName="selected"
className="nav-link"
>About</NavLink>
</div>
</div>
);
}
class Game extends Component {
addDefaultSrc = (ev) => {
ev.target.src = errorIcon;
}
render() {
const { icon, gameTitle, game } = this.props;
return (
<div className="game-box">
<Link
style={{ textDecoration: 'none' }}
to={{
pathname: "/details",
state: { game }
}}>
<div className="game-content">
<img className="game-icon" onError={this.addDefaultSrc} src={icon} alt="icon" />
<p className="game-link"><strong>{gameTitle}</strong></p>
</div>
</Link>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
那是因为当您重新加载页面时,它会尝试访问/games
例如页面。但在github页面上,只有/
or /index.html
页。所以,你会收到 404 错误。
您可能会发现这个答案很有帮助:https://github.com/facebook/create-react-app/issues/1765#issuecomment-285114194 https://github.com/facebook/create-react-app/issues/1765#issuecomment-285114194
从那里:
两种解决方案:
不要在 GitHub 页面上使用 HTML5 历史记录。使用 hashHistory 代替。你的
网址看起来像https://rockchalkwushock.github.io/rcws-development/#path/inside/the/app https://rockchalkwushock.github.io/rcws-development/#path/inside/the/app.
在路由定义中使用 process.env.PUBLIC_URL 以便它们正常工作
无论是在开发中还是部署后。例如: 。这将是空的
开发和 RCWS-development (从主页推断)
生产。
我建议切换到哈希导航策略,这样你的路线就会像blabla.com/#game
代替blabla.com/game
。它将把所有请求路由到您的index.html
,因此您可以使用 React 处理路由。
您可以在此处阅读有关在 React 中使用 HashRouter 的更多信息:https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/HashRouter.md https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/HashRouter.md
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)