我在 gitlab 页面上托管了一个 react-app,我使用 react-router 在使用 historyRouter 的页面之间进行路由。路由工作正常,但是当我重新加载(按 f5 键)或通过将 url 粘贴到我的地址栏中直接打开路由时,该站点会丢失其整个状态。这意味着,例如,我在 myaccount.gitlab/mysite 并且我点击了使用此方法将我重定向到 myaccount.gitlab/mysite/nextpage 的任何链接,
this.props.history.push("/nextpage", {
mystate: this.state.mystate
})
我还将状态 mystate 推送到此页面。到目前为止一切正常,但如果我尝试重新加载页面,我会得到一个空页面。在控制台中调试告诉我 this.location.state 是未定义的。我通过告诉 nextpage 的构造函数将 this.location.state 设置为任何默认值(如果它未定义或为空)成功地解决了这个问题。现在我可以成功重新加载页面,但任何状态都消失了。
有什么可以解决这种行为吗?这只是一个gitlab问题吗?我可以在本地以开发和生产模式在本地运行我的应用程序,并且丢失任何状态或其他东西都没有问题。遵循我使用的一些附加代码:
Gitlab-cli.yml:
test:
image: node:9.6.1
stage: test
script:
- npm install; npm run test
pages:
image: node:9.6.1
stage: deploy
variables:
PUBLIC_URL: "/mypage"
script:
- rm package.json; mv package.json.pages package.json;
npm install;npm install react-scripts@1.1.1 -g;npm run build
- rm -rf public; mv build public
artifacts:
paths:
- public
only:
- master
index.js:
import { Switch, Route, BrowserRouter as Router } from "react-router-dom";
const routing = (
<Router basename={process.env.PUBLIC_URL}>
<div>
<Switch>
<Route exact path="/" component={main} />
<Route path="/nextpage" component={nextPage} />} />
<Route component={PageNotFound} />
</Switch>
</div>
</Router>
);
ReactDOM.render(routing, document.getElementById("root"));