gpt4 book ai didi

reactjs - 重新加载 React Router 应用程序时出现 404 错误

转载 作者:行者123 更新时间:2023-12-05 03:03:59 25 4
gpt4 key购买 nike

当我在本地服务器上重新加载我的应用程序时,一切正常。但是当我在 gh-pages 上托管时重新加载页面时,我收到 404 错误。它不会在主页上执行此操作,但会在其他 2 个页面上执行此操作。它与它被远程托管的事实有关吗?我对 React Router 有点菜鸟。任何帮助将不胜感激。这是相关代码和下面我的应用程序的链接:

React Game App

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页面上,只有/或者/index.html页面。所以,您收到 404 错误。

您可能会发现此答案有帮助:https://github.com/facebook/create-react-app/issues/1765#issuecomment-285114194

从那里:

Two solutions:

Don’t use HTML5 history on GitHub pages. Use hashHistory instead. Your URLs will look like https://rockchalkwushock.github.io/rcws-development/#path/inside/the/app.

Use process.env.PUBLIC_URL in your route definitions so that they work both in development and after deployment. For example: . This will be empty in development and rcws-development (inferred from homepage) in production.

我建议切换到散列导航策略,这样您的路线将看起来像 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

关于reactjs - 重新加载 React Router 应用程序时出现 404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53356587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com