我在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推送到此页面。到目前为止,一切都很正常,但是如果我尝试重新加载页面,我会得到一个emtpy页面。控制台调试告诉我this.location.state是未定义的。我成功地修复了这个问题,告诉nextpage的构造函数,如果this.location.state是未定义的或空的,就将它设置为任何默认值。现在我可以成功地重新加载页面,但是所有状态都消失了。
有什么办法可以纠正这种行为吗?这只是gitlab的问题吗?我可以在本地以开发模式和生产模式在localhost上运行我的应用程序,丢失任何状态或其他东西都不会有任何问题。下面是我使用的一些附加代码:
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"));
发布于 2019-01-15 23:39:57
我相信这不是gitlab相关的问题。这是有意义的,在第一个场景中,你从主页转到nextPage,传递一个参数myState,这样nextPage就可以通过props使用它了。而在第二个版本中,您不知从何而来,所以历史上并没有意识到myState。
一种解决方案是简单地使用lolacstorag
main.js
// instead of:
/*this.props.history.push("/nextpage", {
mystate: this.state.mystate
})
*/
// do:
localStorage.setItem('myState', JSON.stringify(this.state.myState));
nextPage组件
export default class nextPage extends React.Component{
//...
componentDidMount(){
// grap it from localStorage:
let myState = JSON.parse(localStorage.getItem('myState'));
// do whatever you want with it,
// it will be available unless you unset it
}
/... rest of your code..
}
https://stackoverflow.com/questions/54206272
复制相似问题