【问题标题】:React-router and Gitlab pages: Loss of location.stateReact-router 和 Gitlab 页面:丢失 location.state
【发布时间】: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


【解决方案1】:

我相信这不是 gitlab 相关的问题。 这是有道理的,在第一种情况下,您将从主页面转到 nextPage,并传递一个参数 myState,以便通过 props 对 nextPage 可用。 而在第二个中,您不知从何而来,因此历史不知道 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..
   
}

【讨论】:

  • 很高兴,我正打算带你穿过另一条复杂的道路。 redux + redux-persist。
猜你喜欢
  • 2017-02-27
  • 2018-06-04
  • 2020-06-20
  • 2017-09-08
  • 2018-05-13
  • 2019-08-10
  • 1970-01-01
  • 1970-01-01
  • 2021-08-16
相关资源
最近更新 更多