React路由器和Gitlab页面:位置丢失.状态



我在gitlab页面上托管了一个react应用程序,我使用react路由器在页面之间使用historyRouter进行路由。路由工作正常,但当我重新加载(点击f5)或通过将url粘贴到我的地址栏直接打开路由时,网站会失去整个状态。这意味着,例如,我在myaccount.gitlab/mysite,我使用这种方法点击了任何将我重定向到myaccount.git lab/mysite/nextpage的链接,

this.props.history.push("/nextpage", {
mystate: this.state.mystate
})

我也把状态mystate推到这个页面上。到目前为止一切都很好,但如果我尝试重新加载页面,我会得到一个emtpy页面。控制台调试告诉我this.location.state未定义。我告诉nextpage的构造函数,如果this.location.state未定义或为null,则将其设置为任何默认值,从而成功地修复了这个问题。现在我可以成功地重新加载页面,但任何状态都消失了。

有什么办法可以纠正这种行为吗?这只是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"));  

我认为这与gitlab无关。这是有道理的,在第一个场景中,您将从主页转到下一个页面,并传递一个参数myState,这样它就可以通过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));

下一页组件

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..

}

最新更新