【发布时间】:2019-01-15 20:21:45
【问题描述】:
我在 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"));
【问题讨论】:
-
嗯也许可以使用 localstorage 作为选项?
-
你能再解释一下或者举个例子吗?我对所有网络开发都很陌生。它只是一个大学项目
-
localStorage 内置在浏览器中,它允许用户存储有关在页面刷新期间持续存在的站点的信息。 developer.mozilla.org/en-US/docs/Web/API/Window/localStorage robinwieruch.de/local-storage-react 将其视为客户端缓存。历史状态可以达到同样的效果,但根据我的经验,显然在你的经验中,它可能很脆弱或包含一些极端情况。 localStorage 就像一个魅力,你可以使用像 dexie 这样的库来抽象它的用法(localstorage / indexeddb)dexie.org
-
非常感谢您!它有效:)
标签: reactjs react-router gitlab-pages