env*_*bal 3 reactjs react-router
当我在本地服务器上重新加载我的应用程序时,一切都很好。但是当我在 gh-pages 上托管时重新加载页面时,出现 404 错误。它不会在主页上执行此操作,但会在其他两个页面上执行此操作。这是否与远程托管有关?我对 React Router 有点菜鸟。任何帮助将不胜感激。下面是相关代码和我的应用程序的链接:
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'));
Run Code Online (Sandbox Code Playgroud)
这是因为当您重新加载页面时,它会尝试访问/games页面。但在github页面上,只有/or/index.html页面。因此,您会收到 404 错误。
您可能会发现这个答案很有帮助:https://github.com/facebook/create-react-app/issues/1765#issuecomment-285114194
\n\n从那里:
\n\n\n\n\n两种解决方案:
\n\n不要\xe2\x80\x99t 在 GitHub 页面上使用 HTML5 历史记录。请改用 hashHistory。您的 URL 将类似于 https://rockchalkwushock.github.io/rcws-development/#path/inside/the/app。
\n\n在路由定义中使用 process.env.PUBLIC_URL,以便它们在开发中和部署后都可以工作。例如: 。这在开发中和生产中的 rcws-development(从主页推断)中将为空。
\n
我建议切换到哈希导航策略,这样您的路线将看起来像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
\n| 归档时间: |
|
| 查看次数: |
14502 次 |
| 最近记录: |