Bil*_*ill 6 reactjs react-router-v4
在本地,我可以很好地浏览到 /buttons 我什至可以刷新它,它也很好,但是当我将构建目录上传到 github 页面时,我无法访问 /buttons,而是获得了 GitHub 404 页面,而不是我自己的 'notfound ' 页。
如果我创建从主页到 /buttons 的链接,则按钮将加载,但直接浏览它不会加载。
import React, { useState } from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import { Context } from "./components/context";
import { Layout } from "./components/layout";
import { Home } from './routes/home';
import { Buttons } from './routes/buttons';
import { NotFound } from './routes/notfound';
const Router: React.FC = () => {
const [global, setGlobal] = useState({
language: localStorage.getItem("language") || 'en',
apiUrl: 'https://api.domain.com/api',
loggedIn: localStorage.getItem("jwt") ? true : false,
redirectUrl: '',
modal: false,
modalState: '',
});
return (
<Context.Provider value={{ global, setGlobal }}>
<BrowserRouter basename={process.env.PUBLIC_URL}>
<Route render = {({ location }) => (
<Layout location = { location }>
<Switch location = { location }>
<Route exact path = '/' component = { Home } />
<Route exact path = '/buttons/' component = { Buttons } />
<Route component = { NotFound }/>
</Switch>
</Layout>
)} />
</BrowserRouter>
</Context.Provider>
);
}
export { Router };
Run Code Online (Sandbox Code Playgroud)
在 package.json 中,我确实将主页定义为:
"homepage": "https://myName.github.io/myRepo",
pri*_*tam 10
根据https://create-react-app.dev/ 上的部署文档,对于 GH 页面:
GitHub Pages 不支持在底层使用 HTML5
pushState历史 API 的路由器(例如,使用 的 React 路由器browserHistory)。这是因为当 url 有一个新的页面加载时http://user.github.io/todomvc/todos/42,其中/todos/42是前端路由,GitHub Pages 服务器返回 404,因为它对/todos/42.
如果您想将路由器添加到托管在 GitHub Pages 上的项目,这里有几个解决方案:
更改您的路由:
<BrowserRouter basename={process.env.PUBLIC_URL}>
<Route render = {({ location }) => (
<Layout location = { location }>
<Switch location = { location }>
<Route exact path = '/' component = { Home } />
<Route exact path = '/buttons/' component = { Buttons } />
<Route component = { NotFound }/>
</Switch>
</Layout>
)} />
</BrowserRouter>
Run Code Online (Sandbox Code Playgroud)
到:
import { HashRouter, Route, Link } from "react-router-dom";
...
<HashRouter basename={process.env.PUBLIC_URL}>
<Route render = {({ location }) => (
<Layout location = { location }>
<Switch location = { location }>
<Route exact path = '/' component = { Home } />
<Route exact path = '/buttons/' component = { Buttons } />
<Route component = { NotFound }/>
</Switch>
</Layout>
)} />
</HashRouter>
...
Run Code Online (Sandbox Code Playgroud)
index.html使用特殊的重定向参数重定向到您的页面来教 GitHub Pages 处理 404 。404.html在部署项目之前,您需要将带有重定向代码的文件添加到 build 文件夹,并且您需要将处理重定向参数的代码添加到index.html. 您可以在本指南中找到有关此技术的详细说明。| 归档时间: |
|
| 查看次数: |
5394 次 |
| 最近记录: |