简体   繁体   English

设置会话存储并从中获取状态

[英]Setting and getting state from session storage react

So I have a sidenav that has expansion panels that open. 所以我有一个sidenav ,其中有打开的扩展面板。 I'm setting the state on which expansion panel is open. 我正在设置扩展面板state打开状态。 But on click of one of the sidenav , I get redirected to the list item path and the sidenav returns to original state . 但是单击sidenav之一后,我将重定向到列表项路径,并且sidenav返回到原始state on the redirect I'd like for the part of the sidenav that was open to persist. 在重定向中,我希望对sidenav保持开放的部分。 I'm trying to do it like this. 我正在尝试这样做。 I'm not sure why it's not working. 我不确定为什么它不起作用。

 handleOpen = path => {
    this.setState({ openPath: path });
    sessionStorage.setItem('path', this.state.openPath);
  };

class Sidebar extends React.Component {
  constructor(props){
    super(props);
    let getPath = JSON.parse(sessionStorage.getItem('path'))
  this.state = {
    openPath: getPath
  };

  }

You should probably show at least how the component is used but at first glance: 乍一看,您可能应该至少展示该组件的使用方式:

sessionStorage.setItem('path', this.state.openPath);

needs to be 需要是

sessionStorage.setItem('path', JSON.stringify(this.state.openPath));

also I'd reverse these lines: 我也扭转了这些话:

  handleOpen = path => {
    this.setState({ openPath: path });
    sessionStorage.setItem('path', this.state.openPath);
  };

to

  handleOpen = path => {
    sessionStorage.setItem('path', this.state.openPath);
    this.setState({ openPath: path });
  };

It shouldn't matter since Javascript is single threaded but at least stylistically I like to make setState the last expression in any handlers. 没关系,因为Javascript是单线程的,但是至少在样式上,我希望setState成为所有处理程序中的最后一个表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM